0

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.

1
  • Did you post them from your View? You set them as false autogenerated fields, you should put them on your view as hidden fields or set them in your controller by code Commented Jun 11, 2013 at 14:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick. Once I did what you posted and removed the Display annotations everything went without a hitch. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.