Using jqGrid with ASP.NET Web Forms - Part II

This article is continuation of my previous article.

To start of with, we first need to create an asmx web service in JSON format. If you are not sure of 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.

Lets create a web service method called GetListOfPersons. Remember to decorate it with ScriptMethod Attribute as our means of data communication will be in JSON format. In the following example JsonHelper.GetPersons() is responsible for retrieving the list of persons. You can have a appropriate data access logic out there.

[WebMethod]
[ScriptMethod]
public string GetListOfPersons()
{
  List<Person> persons = JsonHelper.GetPersons();
  return Newtonsoft.Json.JsonConvert.SerializeObject(
  new PagedList(persons, persons.Count, 1, persons.Count));
}

Then we create a new instance of PagedList object that we defined in the previous post. Here's one of the constructor that we will be using in case you have forgotten.

public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize);

For simplicity we will not be including features such as paging and sorting for now. (I will include it in later posts.) So, here the rows will be the list of persons retrieved, totalRecords will be the number of persons in the list hence persons.Count, pageIndex will just be simple as 1 as all data will be displayed on the same page number 1. pageSize will be the totalRecords as we don’t want to having paging enabled for now.

Now that the instance of PageList has been created. We need to serialize the object into JSON format which can be recognized easily by jqGrid. To achieve this we make use of Newtonsoft.JSON library by calling the SerializeObject method as shown above.

Now that we are done with the web service, we need to start coding the user interface in HTML and JavaScript.

Create a HTML table along with an ID. This table will be rendered as jqGrid when previewed in the browser.

<table id="table" cellpadding="0" cellspacing="0">
</table>

Include appropriate css style sheets and javascript files required for jqGrid to function. You will need the JQuery UI, and multiselect also. Multiselect JQuery plugin can be obtained from http://quasipartikel.at/multiselect.

<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-1.3.2.min.js") %>"></script>
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/redmond/jquery-ui-1.7.2.custom.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.jqgrid.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.multiselect.css") %>" />
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-ui-1.7.2.custom.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/i18n/grid.locale-en.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/ui.multiselect.js") %>"></script>

Let me write the code first and then explain later on. So it would be easier for you guys to copy paste and learn.

  <script type="text/javascript">
  $(function () {
    $("#table").jqGrid({
      datatype: function (pdata) { getData(pdata); },
      height: 250,
      colNames: ['ID', 'First Name', 'Last Name'],
      colModel: [
        { name: 'ID', width: 60, sortable: false },
        { name: 'FirstName', width: 200, sortable: false },
        { name: 'LastName', width: 200, sortable: false }
      ],
      imgpath: '<%= ResolveClientUrl("~/styles/redmon/images") %>',
      caption: "Sample JSON data retrieved from ASMX web services"
    });
  });
  function getData(pData) {
    $.ajax({
      type: 'POST',
      contentType: "application/json; charset=utf-8",
      url: '<%= ResolveClientUrl("~/WebService.asmx/GetListOfPersons") %>',
      data: '{}',
      dataType: "json",
      success: function (data, textStatus) {
        if (textStatus == "success")
          ReceivedClientData(JSON.parse(getMain(data)).rows);
      },
      error: function (data, textStatus) {
        alert('An error has occured retrieving data!');
      }
    });
  }
  function ReceivedClientData(data) {
    var thegrid = $("#table");
    thegrid.clearGridData();
    for (var i = 0; i < data.length; i++)
      thegrid.addRowData(i + 1, data[i]);
  }
  function getMain(dObj) {
    if (dObj.hasOwnProperty('d'))
      return dObj.d;
    else
      return dObj;
  }
</script>

Query ready function initializes the jqGrid. The data type we have chosen is a custom function with a parameter called pdata. pdata is a short of ParameterData. You can name it what ever you feel comfortable with. It then calls the function called getData. ColName is an array of string containing the column header. ColModal contains more information on how to render data.

Note: The name in ColModal is not the same as ColName but rather its same as that of the list of objects, which was passed as enumerable rows when creating PageList.

Function getData is responsible for doing an AJAX request to the webservice. If success it calls another function called ReceivedClientData. RetrieveClientData function is responsible for appending the data to the grid.

As the data is Ajax request and our response is in string, we need to parse the JSON string to JSON object using json2.js. (We will not be using eval due to security reasons though it is possible.)

GetMain function is used to trip of the “d” property, which is generated by web services if using new versions of ASP.NET for security reasons.

jqGridAspNetWebForms.zip (617.09 kb)

jquery.jqGrid-3.6.zip (274.12 kb)

jquery-ui-1.7.2.custom.zip (745.92 kb)