I was updating a ViewModel property in my Controller, but was not seeing the value updated in my View.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(ManageAgenda manageAgenda)
{
// Save an Agenda and get back a sequence-generated Unique ID
manageAgenda.AgendaId = agenda.AgendaId;
return View(manageAgenda);
}
On my View:
Now, this became REALLY painful because my ID kept coming back as 0, so upon each subsequent save, a brand new record was being created ...@using (Html.BeginForm("Manage", "Agenda", FormMethod.Post, new { @id = "ManageAgendaForm"})) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.AgendaId)
The fix for this turned out to be adding the following line of code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(ManageAgenda manageAgenda)
{
// Save an Agenda and get back a sequence-generated Unique ID
manageAgenda.AgendaId = agenda.AgendaId;
// Send back the Agenda ID.
// Clear out the ModelState so that the ViewModel will be updated in the View.
// See: https://stackoverflow.com/a/9645580/463196
ModelState.Clear();
return View(manageAgenda);
}
What scares me is I *do not understand* why this works. Other comments just described it as a bug in ASP.NET MVC. As a Software Engineer, I do not like fixes I cannot explain to others or myself.
No comments:
Post a Comment