Using the ASP.NET MVC ModelBinder attribute

ASP.NET MVC action methods can be developed using regular method parameters. In earlier versions of the ASP.NET MVC framework, these parameters were all simple types like integers, strings, booleans, … When required, a method parameter can be a complex type like a Contact with Name, Email and Message properties. It is, however, required to add a ModelBinder attribute in this case.

Here’s how a controller action method could look like:

[code:c#]

public ActionResult Contact([ModelBinder(typeof(ContactBinder))]Contact contact)
{
    // Add data to view
    ViewData["name"] = contact.Name;
    ViewData["email"] = contact.Email;
    ViewData["message"] = contact.Message;
    ViewData["title"] = "Succes!";

    // Done!
    return View();
}

[/code]

Notice the ModelBinder attribute on the action method’s contact parameter. It also references the ContactBinder type, which is an implementation of IModelBinder that also has to be created in order to allow complex parameters:

[code:c#]

public class ContactBinder : IModelBinder
{
    #region IModelBinder Members

    public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
    {
        if (modelType == typeof(Contact))
        {
            return new Contact
            {
                Name = controllerContext.HttpContext.Request.Form["name"] ?? "",
                Email = controllerContext.HttpContext.Request.Form["email"] ?? "",
                Message = controllerContext.HttpContext.Request.Form["message"] ?? ""
            };
        }

        return null;
    }

    #endregion
}

[/code]

UPDATE: Also check Timothy's blog post on this one.
UPDATE: And my follow-up blog post.

kick it on DotNetKicks.com

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment

avatar

4 responses

  1. Avatar for Cameron Singe
    Cameron Singe September 1st, 2008

    Excellent, thanks for that.

    I was wondering if I could pass a Guid in as an ID, if it doesn't work out of the box, at least I know I can resort to this. For more complex types I prob rather keep the logic in the actual method not in the binding part, however thats more personal preference.

  2. Avatar for maartenba
    maartenba September 1st, 2008

    Guids are supported out of the box, so that should work nicely.

  3. Avatar for Nathan Stott
    Nathan Stott September 2nd, 2008

    Nice. I didn't know about model binders. I wrote about something similar here though: http://nathan.whiteboard-it...

  4. Avatar for Simone Chiaretta
    Simone Chiaretta September 2nd, 2008

    I don't like Timothy's approach:
    I think that using the ModelBinder to get the id of the object, retrieve the object from the DB and then return it as action parameter is not what the ModelBinder was developed for.

    Maybe it's just a personal feeling, but I think it's a bad idea because one of the key concept of having such an MVC framework is to have separation of concerns, and IMHO the ModelBinding should only be focused on binding the form values to action parameters.

    Maybe in a simple view that shows only the details of a product this might seem a good fit, but what if the view must show more complex data? Like the list of all the products that have an color option in Red? Would you get red from the form value return, do the search in the ModelBinder and send the list of products as action parameter? And what if your action should operate on a more than one model object? or if the data retrieval is conditional to some other logic? Will you put that logic in the ModelBinder?
    Will you have two approach to the same data retrieval problem based on the complexity of the action?

    Furthermore, in this approach I also see a threat to testability: how do you inject the mock repository inside the ModelBinder? It's instantiated directly by the framework, you have no control on how it is instantiated. Maybe during testing you can test it as unit, but how in the production code? How to you inject the dependency on the real repository since you are not the one that is instantiating it?

    I know you didn't write that blog post, but Timothy's blog requires a user registration to write a comment, and I'm not willing to do so.