I am trying to update a news post. The message has a Created date field that is populated when the record was originally created. I do not include this when updating, so when using the method below, this value is null and throws an error.
I am using MVC 5 and Entity Framework 6
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Title,Summary,Content")] Post post) { if (ModelState.IsValid) { db.Entry(post).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(post); }
This method works, but seems a bit awkward.
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Title,Summary,Content")] Post post) { if (ModelState.IsValid) { var newsPost = db.Posts.Find(post.Id); if (newsPost == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } newsPost.Title = post.Title; newsPost.Summary = post.Summary; newsPost.Content = post.Content; db.Entry(newsPost).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(post); }
What is the best method to do this?
Thanks!
source share