I’ve created a default MVC 3 project and created the default edit page for my model. If I don’t touch it, everything work fine.
Now I wanted to remove one of the edit fields on the edit page (because I don’t want the primary key to be editable). So I just changed the EditFor to a DisplayFor. Everything is sown correctly then, but if I want to save I get the following error:
DbUpdateConcurrencyException was unhandled by user code
Store update, insert, or delete statement affected an unexpected
number of rows (0). Entities may have been modified or deleted since
entities were loaded. Refresh ObjectStateManager entries.
In the edit action I can see, that my model class doesn’t get the primary key anymore (it’s 0) and so the update doesn’t work.
// POST: /Weiterleitung/Edit/5
[HttpPost]
public ActionResult Edit(Rufnummern_Weiterleitungen rufnummern_weiterleitungen)
{
if (ModelState.IsValid)
{
db.Entry(rufnummern_weiterleitungen).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(rufnummern_weiterleitungen);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
How can I avoid this error without showing every single field of my model as edit field?
Your POST action misses the Id because a DisplayFor<> doesn’t render a HTML control and the value therefore is not posted back to your controller action. You can either pass the id to your action as a parameter (you then need to add that parameter to your Html.BeginForm()-call in the view and modify your Edit action accordingly) or you can add a HiddenFor<>-field that contains the id. A hidden field is passed on to the controller upon postback and should be recognized by the default binding handler that creates the
Rufnummern_Weiterleitungeninstance from the form values.