I'm working on a project using asp.net MVC with Entity Framework. I was requested to combine the Create page and Edit page together.By another word, if no record , create it, otherwise, edit it. But it brings a problem:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
if(movie.ID ==0)
{
db.Movies.Add(movie);
}
else
{
db.Entry(movie).State = EntityState.Modified;
}
db.SaveChanges();
}
return View(movie);
}
From above code, you can see that I check the property "id" in DBcontext to know whether it's a new record or existed one. But during test, I found that If I create a record without close the webpage,and change some values, press the "save" button in browser again, a new record will be created instead of modify the record just created.
I have traced the whole workflow and found that:
- When I click the Save button first time to create the record, the "id" of movie object does changed after Savechanges function.
- When the browser reload the page after creation, the id property of Model in the webpage is really changed to non-zero.
- But finally the display result of ID on webpage is still zero~!!! So at the second time, the controller get the value from webpage's form element with 0. 4.No matter I use hiddenfor , hidden, editFor in webpage, the result is the same. 5.Since the validation error message shows on webpage is also changed via post method, I think there maybe some internal settings of EF to prevent value change. But even if I deleted AntiForgery attribute from both controller and webpage side, the result is also the same...
Is there anyone who can help?