Display jqGrid using asp .net MVC

Abstract:

jqGrid had been one of the most powerful grids in the HTML world now. It is quite versatile in the offering of features that it competes on part with a lot of other commercial grid solutions. Though it is easy to get started with jqGrid, a few steps are tricky in jqGrid. Though there are helper libraries available, these article try and give a grasp of the basics of how to manually use the jqGrid.

Objective:

We will try and setup one class named as Person with regularly used data types like String, DateTime, int and show the data on the grid in a couple of useful ways. We also have a class PersonRepository which contains a method named GetAll() for us to be used in all our grid.

Setup jqGrid in Project

Visit the current jqgrid download page to download the jqgrid code. You can download everything or atleast Make sure you download the following.

  • Base
  • Table to Grid

The rest of the modules may be useful in later articles.

Basic Display of jqGrid:

A jqGrid can be displayed in 2 ways. The first and most simple way is to draw the table first using asp .net MVC helpers and then call the tableToGrid method of jqGrid in the page load function of jQuery.

A sample snippet for the same is given as below.

	<table  id="persontable"  >
		<tr><th>Name</th><th>Age</th><th>DOB</th><th>Phone</th></tr>
		<tr><td>Steve</td><td>10</td><td>02-01-2002</td><td>321-549-2098</td></tr>
		<tr><td>Bolviski</td><td>12</td><td>02-01-2000</td><td>321-549-2097</td></tr>
		<tr><td>Gates</td><td>30</td><td>02-01-1982</td><td>331-519-1098</td></tr>
	</table>

Make sure to call the css and javascript include files as below. The sample project in our article has put them under http://oursite/scripts/jqgrid/. Also make sure to include the compatible jquery .js file.

		<script src="@Url.Content("~/Scripts/jqGrid/js/jquery-1.5.2.min.js")" type="text/javascript"></script>
		<link href="@Url.Content("~/Scripts/jqGrid/css/ui.jqgrid.css")" rel="stylesheet" type="text/css" />
		<script src="@Url.Content("~/Scripts/jqGrid/js/jquery.jqGrid.src.js")" type="text/javascript"></script>

On the page level or at jquery init, call the tableToGrid function.

		tableToGrid('#persontable');

One can pass multiple options like pager, sort etc., and more options which we will look at later. For a simple program without frills, this would do. But for a complex program, we need to do more.


Display a jqGrid using Controller/Action

This would be the most useful for a program with a little more complexity and above. One will have to retrieve lots of data from database and then display on the grid by sending the json type data to the grid. There is a small trick in generating and sending the data. This is in structuring the data being sent down.

The data has to be structured like the following code snippet. Provide the total number of pages, page number, total records and the rows. If one closely watches the data inside the rows array, it is not exactly json, but just the data.

	{"total":1,"page":1,"records":6,
		"rows":[{"id":1,"cell":["1/2/2002 12:00:00 AM","Steve","321-549-2098","10"]},
				{"id":2,"cell":["1/2/2000 12:00:00 AM","Bolviski","321-549-2097","12"]},
				{"id":3,"cell":["1/2/1982 12:00:00 AM","Gates","331-519-1098","30"]},
				{"id":4,"cell":["1/2/2007 12:00:00 AM","Nixon","251-349-2098","5"]},
				{"id":5,"cell":["1/2/1952 12:00:00 AM","Dixon","548-549-2098","50"]},
				{"id":6,"cell":["1/2/1932 12:00:00 AM","Rutherford","121-549-2058","80"]}
				]}"

So we write our Controller Action named as AjaxGrid which will return such data

        public String GetAjaxGridData()
        {
            List persons = PersonRepository.GetAll();
            ArrayList al = new ArrayList();
            int i=1;
            foreach (Person p in persons)
            {
                var rowdata = new
                {
                    id = i++,
                    cell = p.GetGridString()
                };
                al.Add(rowdata);
            }

            var griddata = new
            {
                total = 1,
                page = 1,
                records = al.Count,
                rows = al.ToArray()
            };

            JavaScriptSerializer js = new JavaScriptSerializer();
            string Serializeddata = js.Serialize(griddata);
            return Serializeddata;
        }

The action page should have the jqGrid ajax call and the table associated to be filled.

        jQuery("#persontable").jqGrid({
            url: '/Home/GetAjaxGridData',
            datatype: "json",
            mtype: 'GET',
            colNames: ['DateOfBirth', 'Name', 'Phone', 'Age'],
            colModel: [
                        { name: 'DateOfBirth', index: 'DateOfBirth', width: 100, align: 'left' },
                        { name: 'Name', index: 'Name', width: 110, align: 'left' },
                        { name: 'Phone', index: 'Phone', width: 110, align: 'left' },
                        { name: 'Age', index: 'Age', width: 90, align: 'left' }
                        ],
            rowNum: 100,
            sortname: 'PositionTime',
            viewrecords: true,
            gridview: true,
            loadonce: true,
            height: 400
        });

The above method will be called in the page load event of jquery and will automatically fill the grid with the data.

Sample:

Click the sample project for jqGrid Display in asp .net MVC for downloading the sample project for Visual Studio 2010.