ASP.NET MVC UpdateModel and TryUpdateModel for DataBinding

Recent ASP.NET MVC Tutorials:

 

ASP.NET MVC has some really nice helpers for databinding and validation that can assist one with a lot of the simple scenarios. I mentioned custom model binders and the ComplexModelBinder, but one can also explicitly call UpdateModel and TryUpdateModel on your controllers to populate custom classes from form values on your Views.

 

ASP.NET MVC UpdateModel

I have a Customer Class with four simple properties.

 

public class Customer
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public decimal Deposit { get; set; }
}

 

I also have a form where the user populates these Customer Properties.

 

MVC UpdateModel

 

We can populate the form values into a Customer instance using either the UpdateModel or TryUpdateModel Methods on our Customer Controller Class. The difference being that TryUpdateModel returns a boolean value if it was successful as opposed to throwing an InvalidOperationException should their be an issue with updating the model.

 

public ActionResult Save()
{
    Customer customer = new Customer();

    try
    {
        UpdateModel(customer, new[] { "Name", "Email",
            "Phone", "Deposit" });
        return RedirectToAction("...");
    }
    catch (InvalidOperationException)
    {
        return View(customer);
    }
}

 

You pass in which properties ( keys ) you want updated by UpdateModel. In this case I am updating “Name“, “Email“, “Phone“, and “Deposit“. Optionally you could pass in an object prefix (e.g. “Customer“) to UpdateModel if you are prefixing your form values with the name of the class, like “Customer.Name“:

 

UpdateModel(customer, new[] { "Name", "Email",
    "Phone", "Deposit" }, "Customer");

 

One of the more interesting aspects of UpdateModel and TryUpdateModel is that they report any errors to the ViewData's ModelState. For example, if I pass in the letter “a“ as the deposit when the property expects a Decimal, an InvalidOperationException is raised and the following error is displayed on the form:

 

MVC UpdateModel and TryUpdateModel

 

Again, I did not add the error via ModelState.AddError. UpdateModel and TryUpdateModel add the error to the ViewData's ModelState so the error is displayed accordingly.

As a word of caution, all of this auto-magic databinding is wonderful for smaller applications, but you need to be careful in larger and more complicated applications as there is a lot of convention over configuration happening here that might limit you as the application evolves. Many of these helper methods can be done with simple factory classes, etc., which are more in your control and can be enhanced as needed.

Hope this helps.

David Hayden

posted on Monday, September 08, 2008 4:44 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices