Using jqGrid with ASP.NET Web Forms - Part I

(As this article grew up to be quite long then I expected, I have broken up this post into different Parts.)

When I first started to use jqGrid few months back, I couldn’t find good tutorials on using jqGrid with ASP.NET webforms. Any search on ASP.NET and jqGrid would lead to ASP.NET MVC tutorial. So, I thought of writing this article to help you guys.

I will be using jqGrid version 3.6 (the codes presented here will most probably work with the earlier versions too – You can download the latest version of jqGrid from http://www.trirand.com/blog or version 3.6 at the end of this article).

We will be using JSON as means of data communication which will be provided by asmx web services. If you don’t know how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery. (Similar concepts can also be applied to WCF RESTful web services.)

How does jqGrid understand our JSON format?

Answering the above question is vital for getting things done right. So lets start with understanding JSON format used by jqGrid.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {"id":"1","cell":["Prabir","Shrestha"]},
        {"id":"2","cell":["Bill","Gates"]},
        {"id":"3","cell":["Steve","Ballmer"]}
    ]
}

Page stands for the current page index. Total represents the total number of pages available and records for the total number records in the entire data list including those not shown in the rows.

Let’s have a closer look at rows. It contains 2 fields, id and cell. The cell contains the main data which needs to be rendered. Here again we have two fields. Try guessing what those fields are.

The first field represents First Name and second field represents Last Name. It is basically an array of string. If others are consuming your web services it would be very difficult for them to actually guess the meaning of these fields. To overcome this difficulty in understanding, lets take an alternative approach. We would then have the result in the following manner.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {id:1,FirstName:"Prabir",LastName:"Shrestha"},
        {id:1,FirstName:"Bill",LastName:"Gates"},
        {id:1,FirstName:"Steve",LastName:"Ballmer"},
    ]
}

The above example is more descriptive and easier to understand. But now another problem arises. How do I convert to that JSON format?

To work with this we create a helper class called PagedList as follows.

using System;
using System.Collections;

public class PagedList
{
    IEnumerable _rows;
    int _totalRecords;
    int _pageIndex;
    int _pageSize;
    object _userData;

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize, object userData)
    {
        _rows = rows;
        _totalRecords = totalRecords;
        _pageIndex = pageIndex;
        _pageSize = pageSize;
        _userData = userData;
    }

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize)
        : this(rows, totalRecords, pageIndex, pageSize, null)
    {
    }

    public int total { get { return (int)Math.Ceiling((decimal)_totalRecords / (decimal)_pageSize); } }

    public int page { get { return _pageIndex; } }

    public int records { get { return _totalRecords; } }

    public IEnumerable rows { get { return _rows; } }

    public object userData { get { return _userData; } }

    public override string ToString()
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(this);
    }
}

Notice that I have included all the fields required by jqGrid. And all these also violates standard C# naming standards. This is to make it easy (Javascript is case sensitive) for us to serialize the object to JSON string understandable by  jqGrid by using the help of Newtonsoft JSON library. Total is also calculated automatically for us.

The rows is basically IEnumerable, which means we can also assign List<T> to it. Which makes our work easier. And since we have overridden the ToString method, converting the object to JSON string representation is far lot easier.

Then how do I put all the things together?

For example lets assume the Person class is declared as below.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and let us also assume that there is a method called GetPersons which returns us a List of Person (List<Person>).

Now to create the PagedList, we simply call the constructor of the PagedList.

PagedList pagedList = new PagedList(GetPersons(), 10, 1, 3);

It will then create a new instance of PagedList and assign the GetPersons List<Person> to rows, 10 to records, 1 to page index and 3 to pageSize.

There is no default constructor for PagedList and it is also an immutable object, which means if you need to change anything you will need to create a new instance of it again. The reason I did this was because, I always used to get confused between total, page and records. So I came up with a solution that I would always use constructor and the parameters in these constructors would be name is such a way that it would not confuse me, so I landed up naming them as pageIndex, pageSize and so on. The other way around would be to use the get and set for all the properties and use the xml documentation features using /// <summary> to prevent the confusion.

This concludes the Part I for Using jqGrid with ASP.NET web forms. In part II, I will be going through on how to actually display it in jqGrid. Stay tuned.

jquery.jqGrid-3.6.zip (274.12 kb)


blog comments powered by Disqus