jQuery Flexigrid Using C# 3.0 (.NET 3.5) & LINQ
1 min read

When I developed my first ASP.NET MVC application, I was a little disappointed with my options for a rich grid. I initially used the grid that is part of the MVCContrib project, but it is pretty simple and there aren’t many features out of the box.

I was very pleased with the code of my MVC application, but the presentation was so 1990's. With all of this new technology I thought the presentation deserved something snappy. That is when I found Flexigrid.

As I mentioned in my last blog entry, I started to use jQuery. To my joy, Flexigrid is a jQuery plugin! Flexigrid uses jQuery to asynchronously populate the contents of the grid using either XML or JSON input.

The following is an example of what the grid looks like. It contains features to sort, page, search, move columns, resize, etc…


The User Interface portion was pretty straightforward to put together. You just need to define your columns, the data source, and some additional parameters (such as: search terms, size, etc…).

I wanted to use this opportunity to try out some new features of .NET 3.5, so I wanted to incorporate LINQ and JSON serialization.

To do this, I needed to setup some classes that the Flexigrid will recognize once serialized. Here is what I came up with.

public class FlexigridViewData
    public int page;
    public int total;
    public List<FlexigridRow> rows = new List<FlexigridRow>();

public class FlexigridRow
    public long id;
    public List<string> cell;

Now is the part where the fun begins. I had already retrieved the content I needed from the Middle Tier. I use LINQ to query the generic list to obtain the correct page subset and then use a helper extension method to serialize the contents to JSON.

public void Page_Load()
    Response.ContentType = "text/x-json";
private string GetPagedContent()
    var pageIndex = Convert.ToInt32(Request.Params["page"]);
    var itemsPerPage = Convert.ToInt32(Request.Params["rp"]);
    var sortName = Request.Params["sortname"];
    var sortOrder = Request.Params["sortorder"];
    var query = Request.Params["query"];
    IEnumerable<Contact> pagedContacts;
    if (string.IsNullOrEmpty(query))
        pagedContacts = sortOrder.Equals("asc") ?
            Contacts.OrderBy(contact => contact.GetPropertyValue<IComparable>(sortName)) :
            Contacts.OrderByDescending(contact => contact.GetPropertyValue<IComparable>(sortName));
        Func<Contact, bool> whereClause = (contact => contact.GetPropertyValue<string>(sortName).Contains(query));
        pagedContacts = sortOrder.Equals("asc", StringComparison.CurrentCultureIgnoreCase) ?
            Contacts.Where(whereClause).OrderByDescending(contact => contact.GetPropertyValue<IComparable>(sortName)) :
            Contacts.Where(whereClause).OrderBy(contact => contact.GetPropertyValue<IComparable>(sortName));

    int count = pagedContacts.Count();
    pagedContacts = pagedContacts.Skip((pageIndex - 1) * itemsPerPage).Take(itemsPerPage);
    const string imageLinkFormat = @"<a href=""{0}""><img src=""{1}"" border=""0"" /></a>";
    const string imageFormat = @"<img src=""{0}"" border=""0"" />";
    var flexigrid = new FlexigridViewData {page = pageIndex, total = count};
    foreach (var contact in pagedContacts)
        flexigrid.rows.Add(new FlexigridRow
            id = contact.ID,
            cell = new List<string>
                string.Format(imageLinkFormat, ResolveUrl("~/Contact.mvc/Detail/" + contact.ID),
    return flexigrid.ToJson();

Here are some helper extension methods that I used to complete the above code snippets.

public static class JsonHelper
    public static string ToJson(this object obj)
        var serializer = new JavaScriptSerializer();
        return serializer.Serialize( obj );
    public static string ToJson(this object obj, int recursionDepth)
        var serializer = new JavaScriptSerializer();
        serializer.RecursionLimit = recursionDepth;
        return serializer.Serialize( obj );

public static T GetPropertyValue<T>( this object component, string propertyName)
    return (T) TypeDescriptor.GetProperties(component)[propertyName].GetValue(component);

As a side note, I did have to dive into the JavaScript and fix two issues that I came across, but other than that it works like a charm. I would prefer if the developer of the product had a better system of tracking bugs and maintaining a forum, but in the meantime what is setup is sufficient.

Edit post on GitHub

Design Pattern Riddle #9
Design Pattern Riddle #8