Understanding ASP.Net MVC Routing and the Model Binder - 9/23/2010
I have been doing ASP.Net MVC for a while now compared to many and one of the largest areas of fascination when I see people first experience MVC is just how clever and powerful the MVC model binder is. Today I caught myself bragging about how great the model binder is yet during this conversation I realized I didn’t really fully understand the magic going on behind the scenes.
As a developer I don’t like not understanding how things work so I decided to take some time to look it up. For starters, unless you have a custom model binder in place, you are using the DefaultModelBinder object out of the box. There are a few additional types that the model binder supports beyond the list below(ex, MVC2 adds binary data support) but for the sake of simplicity the default model binder supports binding to the following items
- Primitive types, such as String , Double, Decimal , or DateTime objects.
- Model classes, such as Person, Address, or Product.
- Collections, such as ICollection
, IList , or IDictionary
Assuming you have a controller action that accepts some combination of these items, the next step is URL Routing. The steps in the process are listed below
- Route Objects are added to the RouteTable in the Global.asax file
- The UrlRoutingModule uses the first matching route object to create the RouteData object which is then used to create a RequestContext object. In doing this the process is
- The route patterns that you have defined or the default route patterns, if any, that are included in your project type.
- The order in which you added them to the Routes collection.
- Any default values that you have provided for a route.
- Any constraints that you have provided for a route.
- Whether you have defined routing to handle requests that match a physical file.
- The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler
- The MvcHandler object uses the RequestContext to identify the IControllerFactory object to create a controller instance with
- The ControllerActionInvoker object that is associated with the controller determines which action method of the controller class and then calls that method
- The route is executed.
I found it fascinating to actually look this up and understand it. Hopefully you enjoy it too!