Wednesday, February 9, 2011

Adding a row filter to System.Web.Helpers.WebGrid

ASP.NET MVC 3 web grid doesn't have a row filter out of the box but it could be easily added in case of need.

Suppose we have such model:

Passing it to a view with the markup showed below

gives this output

We use autocomplete attribute to tell browser do not store previously used filters thus drop-down list won't hide the grid. Also we have attached onchange event handler which will submit the form every time we change the filter value.

Unfortunately if rows in the grid are sorted somehow, applying a filter resets this order. To keep sort order during form submit we should add two hidden inputs:

To obtain necessary values we make use of SortFieldName, SortColumn, SortDirectionFieldName and SortDirection properties of WebGrid class.

As these field values are passed to WebGrid automatically we need only add filter parameter to controller method and use it, for example, in Enumerable.Where() method:

The grid with applied filter looks like:

WebGrid control is smart enough to add current filter value to URLs in grid's header, so sorting doesn't reset filter!


  1. Hey Alexander,

    Thank you very much for posting this.

    Implemented it and it's working perfectly. It would be great if we had a simpler way of getting this functionality out of the box and it'd be much better if it had Ajax support.

    All the best,


  2. is there any way to post form when click sorting, because the sorting affects my filters(having more filters)