ギグを編集するためのフォームがあります。
最初のコントローラ アクションは「編集」と呼ばれます。
フォームは、「更新」と呼ばれる 2 番目のコントローラー アクションに投稿します。
したがって、フォームが投稿されたら、bindingContext.ModelState.AddModelError を使用してモデル状態に検証メッセージを追加する特注の ModelBinder を使用します。
コプトローラーの更新アクションは次のようになります。
[AcceptVerbs("POST")]
public ActionResult Update(Guid id, FormCollection formCollection)
{
Gig gig = GigManager.GetByID(id);
try
{
UpdateModel<Gig>(gig);
GigManager.Save(gig);
return RedirectToAction("List");
}
catch (Exception e)
{
return View(gig);
}
}
モデルバインダーにエラーがある場合、更新モデルによって例外がスローされます。
つまり、RedirectToAction("Edit") が呼び出され、元の "Edit" コントローラー アクションが呼び出されます。
これは、検証メッセージが表示されず、ユーザーがフォームに追加したデータが元の値にリセットされることを意味します!
これにどのようにアプローチすればよいですか?
以下の「編集」アクションを含めました。
[AcceptVerbs("GET")]
public ActionResult Edit(Guid id)
{
Gig gig = GigManager.GetByID(id);
SelectList days = CreateDays(1, 31, 1, gig.StartDate.Day);
ViewData["day"] = days;
SelectList months = CreateMonths(1, 12, 1, gig.StartDate.Month);
ViewData["month"] = months;
SelectList years = CreateYears(DateTime.Now.Year, DateTime.Now.Year + 10, 1, gig.StartDate.Year);
ViewData["year"] = years;
string bandNames ="";
string bandIds = "";
foreach(Act act in gig.Acts)
{
bandNames += act.Name.Trim() + ", ";
if (act.Artist != null)
{
bandIds += act.Artist.ID + ";";
}
}
ViewData["Bands"] = bandNames;
ViewData["BandIds"] = bandIds;
return View(gig);
}
ただし、検証メッセージが表示されません