JqGrid in ASP.Net or SharePoint

This article shows how to use a jqGrid. This approach will work in an ASP.NET application or a SharePoint site. I will try to cover as many properties of jqGrid as I can.

To begin, I added references to the following files in my *.aspx page.

  • jquery-ui-1.8.18.custom.css
  • ui.jqgrid.css
  • jquery-1.7.1.min.js
  • jquery-ui-1.8.18.custom.min.js
  • grid.locale-en.js
  • jquery.jqGrid.min.js
  • json2.js

Files 1 and 4 and the corresponding images files can be downloaded from the jQuery UI ThemeRoller site. And files 2, 5 and 6 can be downloaded from the jqGrid site's download page. (Although I recommend downloading these files from a site that has a working example of jqGrid. The reason I suggest this method is, when I tried downloading these files from the jqGrid's website by selecting the required modules, things worked fine for me initially, but later I reached a point where the jqGrid was not working for me, though there was no problem in my code. Then I replaced the jqGrid JavaScript file that I downloaded from the jqGrid website with a JavaScript file from a site that has a working example and Voila! It worked, without make any changes in my code. This happened to me twice, so perhaps I was doing something wrong but just wanted to let you guys know of this case. This is just like one of those Visual Studio restart things. :) Just kidding.) I will talk about file 7 at the end of this blog.

First let's consider a normal jqGrid with some static data.

Add the following HTML to your page:

  1. <table id="myGrid"></table>  
  2. <div id="pager"></div>  
Add the following JavaScript code (within script tags) to your page (I will be referencing the following code section as “myJqCodeBlock” throughout the article).
  1. var mydata = [{  
  2.     EID: "8",  
  3.     EmployeeName: "Name 1",  
  4.     EmployeeIndex: "10.00",  
  5.     EmployedDate: "2010-05-24",  
  6.     CurrentlyEmployed: true,  
  7.     SiteID: "a"  
  8. }, {  
  9.     EID: "67",  
  10.     EmployeeName: "Name 2",  
  11.     EmployeeIndex: "20.00",  
  12.     EmployedDate: "2010-05-25",  
  13.     CurrentlyEmployed: false,  
  14.     SiteID: "b"  
  15. }, {  
  16.     EID: "34",  
  17.     EmployeeName: "Name 3",  
  18.     EmployeeIndex: "30.00",  
  19.     EmployedDate: "2007-09-01",  
  20.     CurrentlyEmployed: true,  
  21.     SiteID: "c"  
  22. }, {  
  23.     EID: "14",  
  24.     EmployeeName: "Name 4",  
  25.     EmployeeIndex: "10.00",  
  26.     EmployedDate: "2007-10-04",  
  27.     CurrentlyEmployed: false,  
  28.     SiteID: "d"  
  29. }, {  
  30.     EID: "52",  
  31.     EmployeeName: "Name 5",  
  32.     EmployeeIndex: "20.00",  
  33.     EmployedDate: "2007-10-05",  
  34.     CurrentlyEmployed: true,  
  35.     SiteID: "e"  
  36. }, {  
  37.     EID: "6",  
  38.     EmployeeName: "Name 6",  
  39.     EmployeeIndex: "30.00",  
  40.     EmployedDate: "2007-09-06",  
  41.     CurrentlyEmployed: false,  
  42.     SiteID: "f"  
  43. }, {  
  44.     EID: "2",  
  45.     EmployeeName: "Name 7",  
  46.     EmployeeIndex: "10.00",  
  47.     EmployedDate: "2007-10-04",  
  48.     CurrentlyEmployed: true,  
  49.     SiteID: "g"  
  50. }  
  51.   
  52. ];  
  53.   
  54. $(function() {  
  55.     var grid = jQuery("#myGrid");  
  56.     grid.jqGrid({  
  57.         data: mydata,  
  58.         datatype: "local",  
  59.         height: 200,  
  60.         hidegrid: false//hides the arrow button at the top right corner for collapsing the jqGrid  
  61.         rowNum: 10,  
  62.         rowList: [10, 20, 30],  
  63.         viewrecords: true,  
  64.         caption: "Employees",  
  65.         pager: "#pager",  
  66.         colNames: ['EID''Name''Index''Employed Date''Employed''Url'],  
  67.         colModel: [{  
  68.             name: 'EID',  
  69.             index: 'EID',  
  70.             width: 100,  
  71.             align: "center",  
  72.             sorttype: 'int'  
  73.         }, {  
  74.             name: 'EmployeeName',  
  75.             index: 'EmployeeName',  
  76.             width: 100,  
  77.             align: "left"  
  78.         }, {  
  79.             name: 'EmployeeIndex',  
  80.             index: 'EmployeeIndex',  
  81.             width: 100,  
  82.             align: "center"  
  83.         }, {  
  84.             name: 'EmployedDate',  
  85.             index: 'EmployedDate',  
  86.             width: 120,  
  87.             align: "right",  
  88.             formatter: 'date',  
  89.             formatoptions: {  
  90.                 newformat: 'm-d-Y'  
  91.             },  
  92.             datefmt: 'm-d-Y'  
  93.         }, {  
  94.             name: 'CurrentlyEmployed',  
  95.             index: 'CurrentlyEmployed',  
  96.             width: 100,  
  97.             align: "center",  
  98.             formatter: 'checkbox'  
  99.         }, {  
  100.             name: 'SiteID',  
  101.             index: 'SiteID',  
  102.             width: 100,  
  103.             formatter: linkFormatter,  
  104.             sortable: false  
  105.         }]  
  106.     });  
  107. });  
  108.   
  109. function linkFormatter(cellValue, options, rowdata, action) {  
  110.     return "<a href='https://praneethmoka.wordpress.com?rid=" + options.rowId + "' target='_blank'>Click here</a>";  
  111. }  
In the preceding example, I tried to include various possible types of columns (int, float, boolean, string, date, URL) in the grid, just to show how jqGrid handles various datatypes.

So, here's how the jqGrid looks so far.



Both sorting and paging automatically come Out-Of-The-Box for jqGrid. So, you need not go through all the struggle trying to set these up as you would for a Repeater or DataList.

You can also add search functionality to this jqGrid and that can be done in two ways, depending on your preference of UI.

Method 1

Add the following line after line 34 in my “myJqCodeBlock”.
  1. grid.jqGrid('navGrid'"#pager", { edit: false, add: false, del: false, search: true, refresh: true });  
Note: The second parameter (“#pager” in the preceding example) must be the id of the pager div tag in “#id” format. If you try to pass the pager jQuery object, it will blow up.

After adding the preceding line, the jqGrid looks as follows:



See the new buttons added at the bottom-left corner of the jqGrid. One button was added by setting the “search” property to true and the second button was added by setting the “refresh” property to true.

The “refresh/reload” button just reloads the jqGrid data.

Ok, now if you click the “search” button, a new popup (see the image below) will come up where you can specify your search criteria.



Here you can get a wide range of search options all Out-Of-The-Box. Ok, now let's move on to the next method.

Method 2

In the second method, instead of having a search popup for setting your seach criteria, we can create a filter toolbar that appears below the jqGrid column headers as follows:



See the text boxes below each column heading, you can type in your text in these text boxes and as you type in your text, jqGrid content will be filtered automatically without any page refreshes.

To get the preceding Filter Toolbar, add the following code after line 34 in “myJqCodeBlock”.
  1. grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });  
Now, if you don't like jqGrid filtering its content as and when you type your text, you can set the “searchOnEnter” property in the preceding code to true. Then jqGrid's content will be filtered only after you press the “Enter” key on your keyboard.

And while you are playing with the Filter Toolbar, you might notice that the search is not case-sensitive. To make it case-sensitive, all you must do is set the following property in the jqGrid properties.

Add the following property after line 23 in my “myJqCodeBlock”.

ignoreCase: true

If you have already noticed, the way filtering works is, is it looks for records with a column having a value that contains your search text. If you want to change this filtering in a way that jqGrid looks only for records with column having an exact match of your search text, all you must do is change the “defaultSearch” property of the Filter Toolbar property to “eq”. (Check the code below.)
  1. grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "eq" });  
If you want to change the height of the Filter Toolbar, add the following code after setting the Filter Toolbar properties:
  1. var $toolbar = $("tr.ui-search-toolbar", grid[0].grid.hDiv);  
  2. $toolbar.height(30);  
If you want to disable filtering for specific columns, say for columns "Employed" and "Url" in my case, we'll just need to set the search property to false in the corresponding column's colModel property. So, the colModel section of the jqGrid would change as follows:
  1. colModel: [{  
  2.     name: 'EID',  
  3.     index: 'EID',  
  4.     width: 100,  
  5.     align: "center",  
  6.     sorttype: 'int'  
  7. }, {  
  8.     name: 'EmployeeName',  
  9.     index: 'EmployeeName',  
  10.     width: 100,  
  11.     align: "left"  
  12. }, {  
  13.     name: 'EmployeeIndex',  
  14.     index: 'EmployeeIndex',  
  15.     width: 100,  
  16.     align: "center"  
  17. }, {  
  18.     name: 'EmployedDate',  
  19.     index: 'EmployedDate',  
  20.     width: 120,  
  21.     align: "right",  
  22.     formatter: 'date',  
  23.     formatoptions: {  
  24.         newformat: 'm-d-Y'  
  25.     },  
  26.     datefmt: 'm-d-Y'  
  27. }, {  
  28.     name: 'CurrentlyEmployed',  
  29.     index: 'CurrentlyEmployed',  
  30.     width: 100,  
  31.     align: "center",  
  32.     formatter: 'checkbox',  
  33.     search: false  
  34. }, {  
  35.     name: 'SiteID',  
  36.     index: 'SiteID',  
  37.     width: 100,  
  38.     formatter: linkFormatter,  
  39.     sortable: false,  
  40.     search: false  
  41. }]  
And the jqGrid will look as follows:



Notice the difference marked in Red in the highlighted section.

Next, you might sometimes want to show/hide the toolbar at your will. To do this, I added a button to the pager and I called the “toggleToolbar()” function in its onClick event. Add the following code after adding the Filter Toolbar. The code goes as follows:
  1. grid.jqGrid('navButtonAdd'"#pager", {  
  2.     caption: "Search",  
  3.     title: "Search Toolbar",  
  4.     buttonicon: 'ui-icon-search',  
  5.     onClickButton: function() {  
  6.         grid[0].toggleToolbar();  
  7.     }  
  8. });  
  9. grid[0].toggleToolbar(); //To hide the Toolbar initially  
The jqGrid will now have a button at the bottom-left corner as shown below.



Note: To use the “navButtonAdd” method, a “navGrid” method should be called before calling “navButtonAdd”.

Instead of text boxes in the Filter Toolbar, we can also get a Dropdown list that has a list of unique values in a column. Now, let's try changing the TextBox to Dropdown list for the “Name” column.

Add the following functions to your JavaScript code:
  1. function buildSearchSelect(uniqueNames) {  
  2.     var values = ":All";  
  3.     $.each(uniqueNames, function(index) {  
  4.         values += ";" + this + ":" + this;  
  5.     });  
  6.     return values;  
  7. }  
  8.   
  9. function getUniqueNames(uList, columnName) {  
  10.     var uniqueTexts = [],  
  11.         text, textsMap = {}, i;  
  12.     for (i = 0; i < uList.length; i++) {  
  13.         text = uList[i][columnName];  
  14.         if (text !== undefined && textsMap[text] === undefined) {  
  15.             textsMap[text] = true;  
  16.             uniqueTexts.push(text);  
  17.         }  
  18.     }  
  19.     return uniqueTexts;  
  20. }  
  21.   
  22. function setSearchSelect(grid, uList, columnName, filterType) {  
  23.     grid.jqGrid('setColProp', columnName, {  
  24.         stype: 'select',  
  25.         searchoptions: {  
  26.             value: buildSearchSelect(getUniqueNames(uList, columnName)),  
  27.             sopt: [filterType],  
  28.             dataInit: function(elem) {  
  29.                 $(elem).height(20);  
  30.                 $(elem).css('margin-top''2px');  
  31.             }  
  32.         }  
  33.     });  
  34. };  
Then add the “loadComplete” event of the jqGrid after it's colModel properties and call the “setSearchSelect()” by passing the required parameters as follows:
  1. grid.jqGrid({  
  2.     data: mydata,  
  3.     datatype: "local",  
  4.     hidegrid: false,  
  5.     height: 200,  
  6.     rowNum: 10,  
  7.     rowList: [10, 20, 30],  
  8.     viewrecords: true,  
  9.     caption: "Employees",  
  10.     ignoreCase: true,  
  11.     pager: "#pager",  
  12.     colNames: ['EID''Name''Index''Employed Date''Employed''Url'],  
  13.     colModel: [{  
  14.         name: 'EID',  
  15.         index: 'EID',  
  16.         width: 100,  
  17.         align: "center",  
  18.         sorttype: 'int'  
  19.     }, {  
  20.         name: 'EmployeeName',  
  21.         index: 'EmployeeName',  
  22.         width: 100,  
  23.         align: "left"  
  24.     }, {  
  25.         name: 'EmployeeIndex',  
  26.         index: 'EmployeeIndex',  
  27.         width: 100,  
  28.         align: "center"  
  29.     }, {  
  30.         name: 'EmployedDate',  
  31.         index: 'EmployedDate',  
  32.         width: 120,  
  33.         align: "right",  
  34.         formatter: 'date',  
  35.         formatoptions: {  
  36.             newformat: 'm-d-Y'  
  37.         },  
  38.         datefmt: 'm-d-Y'  
  39.     }, {  
  40.         name: 'CurrentlyEmployed',  
  41.         index: 'CurrentlyEmployed',  
  42.         width: 100,  
  43.         align: "center",  
  44.         formatter: 'checkbox',  
  45.         search: false  
  46.     }, {  
  47.         name: 'SiteID',  
  48.         index: 'SiteID',  
  49.         width: 100,  
  50.         formatter: linkFormatter,  
  51.         sortable: false,  
  52.         search: false  
  53.     }],  
  54.     loadComplete: function() {  
  55.         setSearchSelect(grid, mydata, 'EmployeeName''eq');  
  56.     }  
  57. });  
And now the jqGrid turns out to be as:



Ok, now the search part of the jqGrid is over. Let's move on to the next feature.

We can also hide columns in a jqGrid. We can either do this when we set up the colModel properties of the jqGrid or through a line of JavaScript code later based on some condition. To hide the “EID” column, add the “hidden” property in its colModel property.
  1. { name: 'EID', index: 'EID', width: 100, align: "center", sorttype: 'int', hidden: true }  
Or we can say:
  1. grid.jqGrid('hideCol', grid.getGridParam("colModel")[0].name); // 0 indicates first column in this case  
Sometime back when I was looking into some stuff related to jqGrid, I found an interesting functionality for jqGrid in a Stackoverflow post, posted by some guy (unfortunately I don't have the link to that post).

This guy posted some code and using that we can add a button to the Column headers of the jqGrid. The following picture explains what I am talking about.



To add buttons in column headers, add the following JavaScript code after setting up the jqGrid.
  1. grid.closest("div.ui-jqgrid-view").find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-jqgrid-labels > th.ui-th-column > div.ui-jqgrid-sortable")  
  2.     .each(function() {  
  3.     $('<button>').css({  
  4.         float"right",  
  5.         height: "17px"  
  6.     }).appendTo(this).button({  
  7.         icons: {  
  8.             primary: "ui-icon-wrench"  
  9.         },  
  10.         text: false  
  11.     }).click(function(e) {  
  12.         var idPrefix = "jqgh_" + grid[0].id + "_",  
  13.             thId = $(e.target).closest('div.ui-jqgrid-sortable')[0].id;  
  14.         // thId will be like "jqgh_list_name"  
  15.         if (thId.substr(0, idPrefix.length) === idPrefix) {  
  16.             alert('Clicked the button in column "' + thId.substr(idPrefix.length) + '"');  
  17.             return false;  
  18.         }  
  19.     });  
  20. });  
Let's change the data source of the jqGrid now. Sometimes, instead of static data we need to show data from code-behind in jqGrid. This can be done easily and I'll show how this is done.

I created a custom C# class called “Manager”.
  1. public class Manager  
  2. {  
  3.   public int EID { get; set; }  
  4.   public string EName { get; set; }  
  5.   public float EIndex { get; set; }  
  6.   public DateTime EmployedDate { get; set; }  
  7.   public bool CurrentlyEmployed { get; set; }  
  8.  public string SiteID { get; set; }  
  9. }  
And in the code-behind file of my .aspx page I have the following method:
  1. protected string BuildManagers()  
  2. {  
  3.     double d = 10.3;  
  4.     List managers = new List();  
  5.     bool temp = false;  
  6.     for (int i = 0; i < 10; i++)   
  7.     {  
  8.         managers.Add(new Manager  
  9.         {  
  10.             EID = i + 1,  
  11.             EmployeeName = "Name " + i,  
  12.             EmployeeIndex = Math.Round((d + i) / 3, 3),  
  13.             EmployedDate = DateTime.Now,  
  14.             CurrentlyEmployed = temp,  
  15.             SiteID = "a" + (i + 1)  
  16.         });  
  17.         temp = !temp;  
  18.     }  
  19.     System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();  
  20.     return oSerializer.Serialize(managers);  
  21. }  
Then, all we must do is to replace 1-11 in “myJqCodeBlock” with the following line:
  1. <%= var mydata = BuildManagers() %>;  
That's it, now you will be able to see the jqGrid with all the data from your code-behind method.

We can also add data dynamically to jqGrid as in the following:
  1. for(var i = 0; i < mydata.length; i++)  
  2. {  
  3.    grid.jqGrid('addRowData', i + 1, mydata[i]);  
  4. }  
Or:
  1. grid.addJSONData(mydata);  
“mydata” can be either be a static array declared in JavaScript (as we started off with) or it can be a serialized string returned from code-behind or it can be a ResponseText returned from an ajax call.

And the next functionality that I want to discuss is the showing of a jqGrid (sub grid) within a jqGrid. Let's consider the Manager -> Employee hierarchy for this case. I will show all the Managers in the Parent grid and all the Employees under a specific Manager in a sub grid. (The data might not make sense, I just made it up to show the functionality of a sub grid.)

To implement this functionality, instead of loading all the data at once on PageLoad (that might take a lot of time depending on the data size), we will load data (using Ajax and PageMethods in ASP.NET) as we need it.

Let's start.

Create the following C# classes.

Employee.cs
  1. public class Employee  
  2. {  
  3.     public int EID   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public int MID  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string EmployeeName   
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
  19.   
  20. EmployeeManagement.cs(This must be a static class)  
  21.   
  22. public static class EmployeeManagement {  
  23.     public static List GetEmployeesByMID(int ManagerID)  
  24.     {  
  25.         List allEmployees = BuildEmployeesList();  
  26.         return allEmployees.Where(e = > e.MID == ManagerID).ToList();  
  27.     }  
  28.   
  29.     private static List BuildEmployeesList()  
  30.     {  
  31.         List employees = new List();  
  32.   
  33.         employees.Add(new Employee   
  34.         {  
  35.             EID = 1,  
  36.             EmployeeName = "Employee 1",  
  37.             MID = 2  
  38.         });  
  39.   
  40.         employees.Add(new Employee   
  41.         {  
  42.             EID = 2,  
  43.             EmployeeName = "Employee 2",  
  44.             MID = 2  
  45.         });  
  46.   
  47.         employees.Add(new Employee   
  48.         {  
  49.             EID = 3,  
  50.             EmployeeName = "Employee 3",  
  51.             MID = 3  
  52.         });  
  53.   
  54.         return employees;  
  55.     }  
  56. }  
Say my aspx page is called Grid.aspx (this page has all the jqGrid references and code).
Now, in my code-behind file (Grid.aspx.cs), add the following method.
  1. [System.Web.Services.WebMethod(EnableSession = false)]  
  2. public static string GetEmployees(int ManagerID)   
  3. {  
  4.     List employees = EmployeeManagement.GetEmployeesByMID(ManagerID);  
  5.     JavaScriptSerializer serializer = new JavaScriptSerializer();  
  6.     return serializer.Serialize(employees);  
  7. }  
Note: the GetEmployees() method must be a static method for it to be used as a WebMethod.

Now, to get the sub grid add the jqGrid code as follows:
  1. var mydata = ;  
  2. $(function() {  
  3.     var grid = jQuery("#myGrid");  
  4.     grid.jqGrid({  
  5.         data: mydata,  
  6.         datatype: "local",  
  7.         hidegrid: false,  
  8.         height: 250,  
  9.         rowNum: 10,  
  10.         rowList: [10, 20, 30],  
  11.         viewrecords: true,  
  12.         caption: "Employees",  
  13.         ignoreCase: true,  
  14.         pager: "#pager",  
  15.         colNames: ['EID''Name''Index''Employed Date''Employed''Url'],  
  16.         colModel: [{  
  17.             name: 'EID',  
  18.             index: 'EID',  
  19.             width: 100,  
  20.             align: "center",  
  21.             sorttype: 'int'  
  22.         }, {  
  23.             name: 'EmployeeName',  
  24.             index: 'EmployeeName',  
  25.             width: 100,  
  26.             align: "left"  
  27.         }, {  
  28.             name: 'EmployeeIndex',  
  29.             index: 'EmployeeIndex',  
  30.             width: 100,  
  31.             align: "center"  
  32.         }, {  
  33.             name: 'EmployedDate',  
  34.             index: 'EmployedDate',  
  35.             width: 120,  
  36.             align: "right",  
  37.             formatter: 'date',  
  38.             formatoptions: {  
  39.                 newformat: 'm-d-Y'  
  40.             },  
  41.             datefmt: 'm-d-Y'  
  42.         }, {  
  43.             name: 'CurrentlyEmployed',  
  44.             index: 'CurrentlyEmployed',  
  45.             width: 100,  
  46.             align: "center",  
  47.             formatter: 'checkbox',  
  48.             search: false  
  49.         }, {  
  50.             name: 'SiteID',  
  51.             index: 'SiteID',  
  52.             width: 100,  
  53.             formatter: linkFormatter,  
  54.             sortable: false,  
  55.             search: false  
  56.         }],  
  57.         loadComplete: function() {  
  58.             setSearchSelect(grid, mydata, 'EmployeeName''eq');  
  59.         },  
  60.         jsonReader: {  
  61.             userdata: 'Data'  
  62.         },  
  63.         subGrid: true,  
  64.         subGridOptions: {  
  65.             "plusicon""ui-icon-triangle-1-e",  
  66.             "minusicon""ui-icon-triangle-1-s",  
  67.             "openicon""ui-icon-arrowreturn-1-e"  
  68.         },  
  69.         subGridRowExpanded: function(subgrid_id, row_id) {  
  70.             var subgrid_table_id, pager_id;  
  71.             subgrid_table_id = subgrid_id + "_t";  
  72.             pager_id = "p_" + subgrid_table_id;  
  73.             $("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");  
  74.             //To get the selected ManagerID  
  75.             curManagerID = grid.getGridParam('data')[row_id - 1]['EID'];  
  76.   
  77.             var subGrid = $("#" + subgrid_table_id).jqGrid({  
  78.                 datatype: 'jsonstring',  
  79.                 colNames: ['Employee ID''Employee Name'],  
  80.                 colModel: [{  
  81.                     name: "EID",  
  82.                     index: "EID",  
  83.                     width: 100,  
  84.                     key: true,  
  85.                     align: "center",  
  86.                     sorttype: 'int'  
  87.                 }, {  
  88.                     name: "EmployeeName",  
  89.                     index: "EmployeeName",  
  90.                     width: 100,  
  91.                     align: "center"  
  92.                 }],  
  93.                 autowidth: true,  
  94.                 height: '80px',  
  95.                 rowNum: 10,  
  96.                 rowList: [1, 5, 10, 15],  
  97.                 pager: pager_id,  
  98.                 caption: "Employees under this Manager",  
  99.                 hidegrid: false,  
  100.                 ignoreCase: true,  
  101.                 loadComplete: function() {}  
  102.             });  
  103.   
  104.             getData(subgrid_table_id, curManagerID);  
  105.         }  
  106.     });  
Lines 31-65 will set you up with the sub grid. getData() will be the method that loads data into the sub grid when it is opened. Add the following methods to finish up the sub grid code:
  1. function getData(subgrid_table_id, managerID)  
  2. {  
  3.     var param = new Object();  
  4.     param.ManagerID = managerID;  
  5.     $.ajax({  
  6.         type: "POST",  
  7.         url: "Grid.aspx/GetEmployees",  
  8.         data: JSON.stringify(param),  
  9.         contentType: "application/json; charset=utf-8",  
  10.         dataType: 'json',  
  11.         success: function(data, textStatus) {  
  12.             if (textStatus == "success") {  
  13.                 ReceivedClientData(JSON.parse(getMain(data)), subgrid_table_id);  
  14.             }  
  15.         },  
  16.         error: function(msg, error, state) {  
  17.             alert('An error has occured retrieving data!');  
  18.         }  
  19.     });  
  20. }  
  21.   
  22. function ReceivedClientData(data, subgrid_table_id)   
  23. {  
  24.     var thegrid = jQuery("#" + subgrid_table_id);  
  25.     thegrid.clearGridData();  
  26.     for (var i = 0; i < data.length; i++)  
  27.     thegrid.jqGrid('addRowData', i + 1, data[i]);  
  28. }  
  29.   
  30. function getMain(dObj)   
  31. {  
  32.     if (dObj.hasOwnProperty('d')) return dObj.d;  
  33.     else return dObj;  
  34. }  

Now, we'll get a new column (first column) in the parent jqGrid, using which we can get the sub grid that will contain the employees who work under the corresponding Manager. The following image shows the output.



So, that's all the functionality related to jqGrid that I wanted to discuss.

The following are some useful links that have good demos of jqGrid:

http://trirand.com/blog/jqgrid/jqgrid.html
http://www.deloy-dev.com/jgrid_demo_4.0/jqGrid_comprehensive_demo.html

Now, I will explain a couple of errors that one might encounter when using the preceding approach.

json is undefined

You might get a popup message in IE (version < 8) that says "json" is undefined. The issue is that the JSON object is not available in IE 7. You'll want to include JSON2.js on your page for IE < 8 users. This library checks if the browser supports the JSON global object, if it supports it then it will do nothing, otherwise this native implementation will be used. “json2.js” can be downloaded from this link.

The following is another possible error:

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

You will encounter this error when you are using JavaScriptSerializer. To fix this error, be sure you adjust the maximum length of the JSON string in your web.config. By default, the maximum length of a JSON string is 2097152 characters. If the serialized data that you send to the client exceeds this default size then you should change this size accordingly. This size can be changed programmatically using the JavaScriptSerializer.MaxJsonLength property or it can be changed in the web.config as follows.

In code:

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = 2147483644;

In web.config:

  1. < system.web.extensions > < scripting > < webServices > < jsonSerialization maxJsonLength = "2147483644" > < /jsonSerialization>  
  2. </webServices > < /scripting>  
  3. </system.web.extensions >  
Note: The “maxJsonLength” in web.config overrides the JavaScriptSerializer.MaxJsonLength property in the code.

Up Next
    Ebook Download
    View all
    Learn
    View all