Am I an expert? Nah, but I play one on the Internet!

My Resume

Affiliations

Friday, September 30, 2011

ASP.NET MVC Model Binding is a very powerful feature – arguably one of the most valuable features in the entire framework. As with many “very powerful” features, it is also pretty complex and this means that it works great… most of the time… until it doesn’t.

One of the biggest questions is “where are these values coming from”? The simple answer to this question is: the Request object. The Request object is a core ASP.NET object - a dictionary of values aggregated from various sources such as the querystring (URL), form post values, and server variables. The Request object is nothing new – it’s been around in one form or another since the days of ASP!

Ok, so you know how I just said that the model binding values come from the Request object? Uh… that was kind of a lie. The truth is that they come from ValueProviders (created by ValueProviderFactories). These value providers try to retrieve values from the same places - in the same order - as the Request object. Don’t believe me? Have a look at the source:

public static class ValueProviderFactories {

private static readonly ValueProviderFactoryCollection _factories = new ValueProviderFactoryCollection() { new ChildActionValueProviderFactory(), new FormValueProviderFactory(), new JsonValueProviderFactory(), new RouteDataValueProviderFactory(), new QueryStringValueProviderFactory(), new HttpFileCollectionValueProviderFactory(), };

In this way, the order of the default collection of Value Providers essentially mimics the Request object… which is why you are usually pretty safe in considering them “the same” even when they’re not.