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

  1. Route Objects are added to the RouteTable in the Global.asax file
  2. 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.
  3. The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler
  4. The MvcHandler object uses the RequestContext to identify the IControllerFactory object to create a controller instance with
  5. The ControllerActionInvoker object that is associated with the controller determines which action method of the controller class and then calls that method
  6. The route is executed.
  7. I found it fascinating to actually look this up and understand it. Hopefully you enjoy it too!

    Share this article

    Other Blogs

    Getting Started with the Telerik MVC Extensions - 2/12/2012
    Codemash 2012 Recap & Pictures - 1/14/2012
    Findlay Area .Net Users Group(FANUG) - Improving Software Quality with Continuous Integration, and An Introduction to FluentMigrator - 9/28/2011
    MVC3 Unobtrusive Validation With MVC Contrib - 8/14/2011
    Automating SSRS Report Deployment for CI - 7/10/2011