OdeToCode IC Logo

Hard Working Model Binder

Wednesday, July 14, 2010

The job of a model binder in ASP.NET MVC is to take pieces of data in an HTTP request and place them into objects. It's easy to sense a model binder at work when you use one of the Update API's.

bool success = TryUpdateModel(movie); // here

// .. or ...

try
{
    UpdateModel(movie); // here, too!
}
catch (InvalidOperationException ex)
{
    // ... model binding errors ...
}

If the first line of code with TryUpdateModel could speak, it would say something like "Here is a movie. I want you to look around and find information to populate the movie. Go look in the posted form values, in the routing data picked out of the URL, and in the query string to see if you can find something called "Title". If you do find a title, move the value into the "Title" property of the movie. Do the same for "TagLine", "Summary", and the rest of my movie properties, and do it fast!".

Ok, it doesn't really say "do it fast", but we'd like to think it will be fast.

Conceptually, a model binder is a match maker who pairs things together based on their name.

Binding - Not Just For Models

unhappy by gagilas.The "model" part of the model binding name does lead to some confusion.

Don't tell the model objects this because they might get upset - but models aren't special.

A model binder can work against any type of object. The object doesn't have to be an official "model" or even complex type. In fact, a model binder might be at work in more places than you suspect.

Take, for example, the following HTTP GET request.

http://server/home/index/3

or

http://server/home/index?id=3

Assuming you have the default routing rule in place, a model binder runs to execute this action:

public ActionResult Index(int id)
{
    // ...
}

When an action is invoked, the action invoker sees the id parameter and asks a model binder to bind the parameter. Unless you've configured a different model binder, then it is the MVC DefaultModelBinder that will locate the value for "id". The model binder will find this value in the routing data (if the URL used is index/3), or it will find it in the query string (if the URL is index?id=3).

In summary, model binding isn't just for updating model objects in an HTTP POST. There is a model binder at work for simple parameter types like integers during mundane HTTP GET requests. We'll need to remember this fact when we look at more characteristics of these hard-working, recursive MVC denizens in a future post.