Reputation: 1279
I'm working on a small ASP.NET MVC4 web app with Entity Framework linking the app with my database. I let Visual Studio 2012 generate all the CRUD operations in the controller and views, and everything works OK except for Edit.
My generated object is as follows:
public partial class Post
{
public Post()
{
this.Attachment = new HashSet<Attachment>();
}
[Display(AutoGenerateField = false)]
public int post_id { get; set; } // This is the PK of my table
public string title { get; set; }
public string text { get; set; }
[Display(AutoGenerateField = false)]
public System.DateTime created { get; set; }
[Display(AutoGenerateField = false)]
public Nullable<System.DateTime> modified { get; set; }
[Display(AutoGenerateField = false)]
public string author { get; set; } // This is a FK from the "author" table
public virtual ICollection<Attachment> Attachment { get; set; }
public virtual Author Author1 { get; set; }
}
And the Edit POST operation is as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Post post)
{
if (ModelState.IsValid)
{
post.modified = DateTime.Now;
db.Entry(post).State = EntityState.Modified;
db.SaveChanges(); // DbUpdateConcurrencyException thrown here
return RedirectToAction("Index");
}
ViewBag.author = new SelectList(db.Author, "author1", "password", post.author);
return View(post);
}
When I submit the edited post, ASP.NET spits out a DbUpdateConcurrencyException saying that the operation affected an unexpected number of rows (0).
When debugging, I found out that author, created and post_id are null; all of them should keep their values.
How can I fix this?
Thanks in advance.
Upvotes: 0
Views: 494
Reputation: 5632
On your Edit View() you should add these properties in hidden fields:
@Html.HiddenFor(m => m.post_id) etc.
That way they gonna bind on post model and you can use them in your edit method.
Upvotes: 1