ASP.NET MVC – SortDirection model binder

I’ve recently been working on an ASP.NET MVC 3 project. Yesterday I started working with the WebGrid that comes built-in. One thing that didn’t sit right with me was that the WebGrid posts the sort direction to your controller as either “ASC” or “DESC”, yet in the API when setting up the WebGrid in a view (we’re using Razor) you specify the sort direction using the enum System.Web.UI.WebControls.SortDirection.

I initially tried simply changing the sort direction parameter to be of type SortDirection. This doesn’t work though because the values posted by the WebGrid aren’t string equivalents to the enum values (ie. “Ascending” and “Descending”). So, to fix this problem, I decided to build out a custom model binder. Model Binders in ASP.NET MVC are the pieces that map the data provided by the client (browser) to your controller action parameters.

So here’s the model binder that I came up with.

using System.Web.Mvc;
using System.Web.UI.WebControls;

public class SortDirectionModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (string.IsNullOrEmpty(bindingContext.ModelName))
        {
            return null;
        }

        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (valueResult == null)
        {
            return null;
        }

        if (valueResult.AttemptedValue.IsNullOrWhiteSpace() || valueResult.AttemptedValue == "ASC")
        {
            return SortDirection.Ascending;
        }
        else
        {
            return SortDirection.Descending;
        }
    }
}

In the model binder we simply grab the posted value and determine if we need to return SortDirection.Ascending or SortDirection.Descending. Once we have the model binder written, we need to let ASP.NET MVC know about it by adding it to the ModelBinders.Binders dictionary. I put this code in the Global.asax file like this:

public class MyApplication : HttpApplication
{
    protected void Application_Start()
    {
        ModelBinders.Binders[System.Web.UI.WebControls.SortDirection] = new SortDirectionModelBinder();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s