MvcContrib Grid Part 6 - Sorting

This is part 6 of a series about the MvcContrib Grid.

I recently added single-column sorting support to the MvcContrib grid. This can be turned on by calling the “Sort” method on a grid declaration and accepting a parameter of type GridSortOptions in your controller actions.

Controller:

public ActionResult Sorting(GridSortOptions sort) 
{
  ViewData["sort"] = sort;
  var people = _peopleFactory.CreatePeople();
 
  if(!string.IsNullOrEmpty(sort.Column)) {
    people = people.OrderBy(sort.Column, sort.Direction);
  }
 
  return View(people);
}

View:

<%= Html.Grid(Model)
  .Sort(ViewData["sort"] as GridSortOptions)
  .Columns(column => {
      column.For(x => x.Id).Named("Person ID");
      column.For(x => x.Name);
      column.For(x => x.Gender);
      column.For(x => x.DateOfBirth).Format("{0:d}");
    }) %>

By calling the “Sort” method, this tells the grid that sorting should be enabled. This will generate sorting links for each column heading (note that currently sorting is enabled for all columns – there is no way to enable it for individual columns only. I’ll change this in a future release)

These sorting links will add two additional parameters to the querystring: Column and Direction. These can be handled in your controller action by taking as a parameter an object of type GridSortOptions.

Using this object, you can then sort your data using whatever mechanism you choose. Out of the box, MvcContrib provides an overload for the “OrderBy” extension method that takes a property name and a direction and delegates the sorting to IQueryable. However, use of this extension method is entirely optional.

This also works with the grid’s paging support, so if you want your data to be both paged and sorted then you can make a call to AsPagination (or by using a custom IPagination provider) after the call to OrderBy:

public ActionResult SortingAndPaging(int? page, GridSortOptions sort) 
{
  ViewData["sort"] = sort;
  var people = _peopleFactory.CreatePeople();
 
  if (!string.IsNullOrEmpty(sort.Column)) {
    people = people.OrderBy(sort.Column, sort.Direction);
  }
 
  people = people.AsPagination(page ?? 1, 10);
 
  return View(people);
}

…and the results will be as expected.

When a column is sorted, the CSS classes of “sort_asc” or “sort_desc” will be applied to the relevant <th> element, so you can style the column headings (for example, by adding up/down arrows).

Written on March 14, 2010