Basics of ASP.NET MVC Model Binding

In this blog I will document some of the basics of mvc model binding. Model binding is the process when action parameters are populated from the ASP.NET request data. Two things happen in this process - collecting data from the request and populating the model with that data. The first part is achieved by value providers and the second part is achieved via model binders.

The request data can come in many forms such as querystrings, form fields and route data. MVC uses the value provider factories to read the request data. The order in which it reads is - 
  • action parameters for child action, 
  • Request.Form (form fields), 
  • Request.InputStream for ajax operations, 
  • RouteData.Values (route data), 
  • Request.QueryString, 
  • Request.Files.
As with most things in MVC, you can create your own custom value providers. A custom value provider can be created by implementing the ValueProviderFactory interface.
The DefaultModelBinder uses recursion to populate the model. If the value provided is a simple type it tries to convert it to the target type. If its complex type, it will recursively try to bind it until it reaches the simple types. If you have an action method like ActionResult DoSomething (IProduct product), since the parameter is an interface type, the model binder will not work correctly. It will throw an error on the lines of unable to create instance for an interface type. Similar behavior will occur if you have an abstract class. In such instances, we need to extend and create our own Model Binders. A custom model binder can be created by implementing the interface IModelBinder.