ASP.NET MVC TryUpdateModel vs UpdateModel

I have answered this question a few times now so I figured I'd throw up a quick post about it; hopefully Google will catch it when future people inquire.

If you are used to coding against ASP.NET MVC then you are aware of model binding and the associated risks it poses. Many times you will have to explicitly call model binding in order to better control how and what the model binder is allowed to bind. There are two ways to invoke the default model binder.

UpdateModel

public ActionResult Create()  
{
    Entity myEntity = new Entity();
    UpdateModel(myEntity);
}

What we just did here was explicitly invoke the model binder and tell it to bind the request values to the object, just as if we had asked for it in the arguments. The difference here is that if it has any issues while binding properties it will throw an exception. It will halt your application and inform you that there was a binding error. I have rarely found an instance where I want to explicitly invoke model binding and also have it throw an exception on binding errors, but if that need ever arises, you have it available.

TryUpdateModel

public ActionResult Create()  
{
    Entity myEntity = new Entity();
    TryUpdateModel(myEntity);

    if (ModelState.IsValid)
    {
        // ...
    }
}

TryUpdateModel does not throw an exception if it runs into binding errors. Instead it logs the error in the model state dictionary. This enables you to check the ModelState.IsValid boolean at your convenience and decide what to do from there. This is an important distinction to be made because if we had used UpdateModel then our if (ModelState.IsValid) would not be hit in the event of a failure to bind.

Why explicitly invoke model binding?

It is true that in both the methods above it would just be easier to let model binding run on its own.

public ActionResult Creat(Entity myEntity)  
{
    if (ModelState.IsValid)
    {
        // Implicit model binding operates like TryUpdateModel.
        // It does not throw an exception on binding failures.
    }
}

Most of the time this is what you will likely do. But in scenarios where you want to limit what can be bound, explicitly invoking model binding is very useful. For more information on why you might want to explicitly invoke model binding, see my post on model binding security.

Chev

Read more posts by this author.

comments powered by Disqus