When and why do you use TryUpdateModel in asp.net mvc 2?

C#asp.netasp.net Mvc

C# Problem Overview


I can't seem to find just a basic code sample to see how TryUpdateModel works? When do you use it and why?

C# Solutions


Solution 1 - C#

You can use this method to update the model that backs a particular view via the given controller. For example, if I have a view displaying a Foo object with property Bar populated by a textbox, I can call a method Save() on the controller and call TryUpdateModel to attempt to update the Foo.

public class Foo {
  public string Bar { get; set; }
}

// ... in the controller
public ActionResult Save() {
  var myFoo = new Foo();
  TryUpdateModel(myFoo);
}

This will try to update the model with the given value for Bar. If the update fails validation (say, for example, that Bar was an integer and the textbox had the text "hello" in it) then TryUpdateModel will pass update the ViewData ModelState with validation errors and your view will display the validation errors.

Make sure you pay close attention to the security warning for .NET Framework 4 in the MSDN documentation:

> Security Note Use one of the > [Overload:System.Web.Mvc.Controller.TryUpdateModel``1] > methods that takes either a list of > properties to include (a whitelist) or > a list of properties to exclude (a > blacklist). If no explicit whitelist > or blacklist is passed, the > [Overload:System.Web.Mvc.Controller.TryUpdateModel`1] > method tries to update every public > property in the model for which there > is a corresponding value in the > request. A malicious user could > exploit this in order to update > properties that you do not intend to > provide access to.

https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.100).aspx

Solution 2 - C#

TryUpdateModel() allows you to bind parameters to your model inside your action. This is useful if you want to load your model from a database then update it based on user input rather than taking the entire model from user input.

public ActionResult Update(int id) {
    var service = new ServiceClass();
    var record = service.LoadModel(id);
    if (!TryUpdateModel(record)) {
        // There was an error binding data
        return View();
    }
    // Everything was ok, now save the record back to the database
    service.SaveModel(record);
    return View("Success");
}

It acts similar to UpdateModel() in this respect but returns true on success and false if there is an error. UpdateModel() throws an exception if there is an error which requires a bit more code.

> Note: You might want to use one of the overloads that allows you to > limit which properties can be updated.

Solution 3 - C#

We also used TryUpdateModel to avoid Model Binding magic before the Action was called; instead we took a HttpFormCollection as our parameter and called TryUpdateModel within the method. The clean boolean value returned from this allowed control flow to be passed to a Success or Failure method for the Action. e.g.

public ActionResult Save(HttpFormCollection formCollection)
{
  var saveModel = new SaveModel(); // or from a Factory etc
  var validModel = TryUpdateModel(_saveModel, formCollection); // order may be incorrect
  return validModel ? Save(saveModel) : InvalidSaveModel(saveModel);
}

We found it quite easy to build a HttpFormCollection for all our validation cases and therefore test the action.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser603007View Question on Stackoverflow
Solution 1 - C#Martin DomsView Answer on Stackoverflow
Solution 2 - C#ASP.NET MVC TipsView Answer on Stackoverflow
Solution 3 - C#CiaranView Answer on Stackoverflow