.NET CoreのEntityFrameworkとMVCを使用しており、処理方法がわからないという問題が発生しています。私はPassword
フィールドのUserモデルを持っています。ユーザーモデルを編集したいのですが、Password
フィールドを残りのユーザーフィールドと同じ編集ビューに表示したくありません。パスワードを隠すのは簡単ですが、編集を保存するときに、モデルは常に検証に失敗します。Model Validation Failureの原因となるモデルのパスワードフィールドを除外します
私は、動作するビューでパスワードフィールドを隠しているだけで、パスワードをページソースに表示したままにしていました。私もUserEditView
モデルを作成しようとしましたが、それは達成しようとしているものに必要ではないはずの翻訳コードをたくさん作成します。
ご協力いただければ幸いです。以下は私が作業しているコードです。
モデル: User.cs
public class User
{
[Display(Name="User ID")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required()]
[Display(Name="Email Address")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required()]
public string Name { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required()]
public string Salt { get; set; }
}
編集アクション: UsersController.csあなたのコントローラで
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees.SingleOrDefaultAsync(m => m.ID == id);
if (employee == null)
{
return NotFound();
}
ViewData["LocationID"] = new SelectList(_context.Locations, "ID", "Address", employee.LocationID);
ViewData["PositionID"] = new SelectList(_context.Jobs, "ID", "Name", employee.PositionID);
return View(employee);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Email,Name,LocationID,PositionID")] Employee employee)
{
if (id != employee.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(employee);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(employee.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["LocationID"] = new SelectList(_context.Locations, "ID", "Address", employee.LocationID);
ViewData["PositionID"] = new SelectList(_context.Jobs, "ID", "Name", employee.PositionID);
return View(employee);
}
モデルにそのプロパティがないように変更します。特定のビュー用に設計されたモデルを持つことには間違いがありません。実際、MVCのポイントのようなものです。 – Crowcoder
送信されたIDからパスワードを検索し、employee.password = [ルックアップパスワード]を設定して保存できますか?私はビューにパスワードを公開しませんが、コントローラでそれを行うのに問題はありません。 – Aaron
@Crowcoderそれは私が試したことの1つですが、エンティティフレームワークを使用していて、私が試したときにコントローラを足場で縛って、 'UserEditViewModel'テーブルが存在しないというエラーが発生しました。 – TheDude