I’ve been using .net MVC for a year or two now, and this question has always been unanswered in my books. Let me demonstrate a very simple example
PersonViewModel
public class PersonViewModel
{
public Person person { get; set; } //person is a db generated object
public SelectList jobtypes { get; set; } // drop down list for this view
}
PersonController
public ActionResult Edit( int id )
{
PersonViewModel model = new PersonViewModel();
model.person = db.GetPerson(id); //get a person from the db
model.jobtypes = GetThemJobTypes();
return View(model);
}
now the question is which of the following i should do?
[HttpPost]
public ActionResult Edit ( PersonViewModel model )
{
Person person = db.GetPerson(model.person.personid);
person.firstname = model.person.firstname;
person.lastname = model.person.lastname;
person.jobtypeid = model.person.jobtypeid;
person.save();
person.favoritetoy.name = model.person.favoritetoy.name;
person.favoritetoy.save();
}
OR
[HttpPost]
public ActionResult Edit (int id, FormCollection formValues)
{
Person person = db.GetPerson(id);
UpdateModel(person, "person");
person.save()
UpdateModel(person.favoritetoy, "favoritetoy");
person.favoritetoy.save()
}
It seems like the formcollection method with updatemodel is the method of choice everywhere around the web. What i’m a little conflicted with is that we already have a ViewModel with the fields we want, why use the formcollection again? Many has also pointed out to strictly use the viewmodel in the post, but I haven’t seen good example of an update to db models using that method.
What is the Intended way of updating db objects?
There’s really no intended way. Unlike Ruby on Rails the ASP.Net MVC framework doesn’t tie you into any particular pattern for your controller and model interactions. Personally I use something closer to the first because it’s more likely to cause a compiler error if you make a mistake than a runtime error. I would recommend moving this code to a location other than your controller method however as it will grow quickly out of hand.