Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to update only some fields of an object in MVC?

I am trying to update a news post. The post has a date field called Created that is populated when the record is initially created. I don't include this when updating, so when using the below method, this 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 does work but it seems a bit clunky.

[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 practice method of doing this?

Thanks!

like image 232
Unw0und Avatar asked Jun 16 '15 10:06

Unw0und


People also ask

What is update model in MVC?

I am using the same example in this article. We can also use UpdateModel method to fetch data from view to controller. UpdateModel is the method which is generics type and takes parameter of model type. This method fills the value to the property of this model class.

How do you update related entities in Entity Framework Core?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.


1 Answers

EF also has a simple built-in "AutoMapper" that works with scalar values.

public class PostViewModel()
{
     public string Id {get;set;}
     public string Title {get;set;}
     public string Summary {get;set;}
     public string Content {get;set;}
}

public ActionResult Edit(PostViewModel viewModel)
{
    if (ModelState.IsValid) {
        var newsPost = db.Posts.Find(post.Id);
        ...
        db.Entry(newsPost).CurrentValues.SetValues(viewModel);
        ...
    }
}
like image 84
James Sampica Avatar answered Oct 16 '22 08:10

James Sampica