Thursday 10 September 2009

UpdateModel() and TryUpdateModel()

Model objects can be easily updated with form values using either the UpdateModel() or TryUpdateModel() methods on the Controller class. These methods are overloaded and there are a lot of variations but at its simplest the methods need only take a TModel.
[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Edit(int id, FormCollection formValues) 
{ 
    Dinner dinner = _dinnerRepository.GetDinner(id); 
    UpdateModel(dinner); 
    _dinnerRepository.Save(); 

    return RedirectToAction("Details", new { id = dinner.DinnerId }); 
}

TryUpdateModel returns a boolean value if the update was successful. UpdateModel throws an InvalidOperationException should there be an problem with updating the model. UpdateModel and TryUpdateModel report any errors to the ViewData's ModelState; you don't have to add them via ModelState.AddError yourself.

The overloadde methods allow you to specify specific keys which are used to map object properties to form values. You can also optionally specify an object prefix for cases where form element names are in the form Prefix.ElementName (e.g. Dinner.Title).