Introduction
This article presents a simple example on how to use jQuery Grid Plugin in MVC.
Background
This is the part one of the article to present an example on how to use "jQuery Grid Plugin". The example will show you how to implement a read-only grid. This article tries to answer the following questions:
- What is the minimum set of the JavaScript libraries and CSS styles that you need to download to use "jQuery Grid Plugin".
- How to implement a basic grid.
- How to implement the paging, sorting, and searching capabilities for the grid.
The "jQuery Grid Plugin" uses "Ajax" calls to obtain the data from the server to display. We can use many platforms such as "PHP" to implement the server code to serve the "Ajax" calls. In this example, the server code is implemented in an ASP.NET "MVC" controller.
This article assumes that you have some basic knowledge in "jQuery" and "MVC". If you are new to these subjects, you can easily find reference materials over the internet.
The Visual Studio Solution
To create a minimally functional grid using the "jQuery Grid Plugin", you need to download the following components:
- You will need the "jQuery" script library. You can download it from here. The version used in this example is "1.6.2".
- You will need the script library and some CSS styles from the "jQuery Grid Plugin". You can download them from here. At minimum, you will need the two JavaScript files "jquery.jqGrid.min.js" and "grid.locale-en.js". You will also need the CCS file "ui.jqgrid.css". The "jQuery Grid Plugin" used in this example is version "4.1.2".
- The "jQuery Grid Plugin" uses some of the CSS styles from the "jQuery UI". You can download the "jQuery UI" from here. To create a basic grid, you do not need the JavaScript file from the "jQuery UI". You will only need the CSS style. The CSS styles from the "jQuery UI" come in different "themes". The "theme" used in this example is "redmond". The CSS styles used in this example come from the version "1.8.14".
In the solution explorer, you can see that I put all the downloaded JavaScript files in the "Scripts" folder and all the downloaded CSS style sheets and image files in the "Content" folder. Besides the downloaded files, the following files are related to the creation of the grid using the "jQuery Grid Plugin" in this example:
- The "StudentRepository.cs" in the "Models" folder is the application's data model. It maintains the data for the grid to display.
- The "Default.htm" is the file where the grid is created. It has the HTML components and the JavaScript code to create the grid.
- The MVC controller "jQGridController.cs" in the "Controllers" folder implements the server code to serve the "Ajax" calls issued by the "jQuery Grid Plugin".
The sole purpose of the MVC controller "HomeController.cs" in the "Controllers" folder is to make the "Default.htm" file the default web page of this MVC application. If the user does not specify the controller and the action in the url, this file is responsible to re-direct it to the "Default.htm" page. The "HomeController.cs" is implemented as the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace jqGridExamplePart1.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return new RedirectResult(Url.Content("~/Default.htm"));
}
}
}
Let us now take a look at how we can create a read-only grid using "jQuery Grid Plugin" starting with the application's data model.
The Data Model
The application's data model is implemented in the "StudentRepository.cs" in the "Models" folder:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace jqGridExamplePart1.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Score { get; set; }
public DateTime Enrollment { get; set; }
}
public static class StudentRepository
{
private static readonly List<Student> Students = new List<Student>();
public static List<Student> GetStudents() { return Students; }
static StudentRepository()
{
int total = 105;
DateTime now = DateTime.Now;
var scoreRand = new Random();
var enrollmentRand = new Random();
for (int i = 1; i <= total; i++)
{
var student = new Student();
student.Id = i;
student.Name = "Name No." + i.ToString();
student.Score = 60
+ Convert.ToInt16(scoreRand.NextDouble() * 40);
student.Enrollment
= now.AddDays(-1 * (int)(enrollmentRand.NextDouble() * 365 * 10));
Students.Add(student);
}
}
}
}
- The "
Student
" class defines some basic information for a student. - The
static
class "StudentRepository
" maintains a list of students. We can use the "GetStudents
" method to access the student list.
The list of students in the "StudentRepository
" class will be displayed in the grid created in the "Default.htm" page in this example.
The "Default.htm" Page
The "Default.htm" page is implemented as the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jqGrid Example Part 1</title>
<link rel="stylesheet"
href="Content/jquery-ui/redmond/jquery-ui-1.8.14.custom.css"
type="text/css" />
<link rel="stylesheet"
href="Content/jquery-grid/ui.jqgrid.css" type="text/css" />
<script src="Scripts/jquery-1.6.2.min.js"
type="text/javascript"></script>
<script src="Scripts/jquery-grid/grid.locale-en.js"
type="text/javascript"></script>
<script src="Scripts/jquery-grid/jquery.jqGrid.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var jqDataUrl = "jQGrid/LoadjqData";
$(document).ready(function () {
$("#jqTable").jqGrid({
url: jqDataUrl,
datatype: "json",
mtype: "POST",
colNames: ["Id", "Name", "Score", "Enrollment"],
colModel: [
{ name: "Id", index: "Id", width: 40, align: "left" },
{ name: "Name", index: "Name", width: 100, align: "left" },
{ name: "Score", index: "Score", width: 200, align: "left" },
{ name: "Enrollment", index: "Enrollment", width: 200, align: "left"}],
width: 550,
height: 200,
toppager: true,
pager: $("#jqTablePager"),
rowNum: 5,
rowList: [5, 10, 20],
viewrecords: true,
sortname: "Id",
sortorder: "asc",
caption: "A Basic jqGrid - Read Only"
}).navGrid("#jqTablePager",
{ refresh: true, add: false, edit: false, del: false },
{},
{},
{},
{sopt: ["cn"]}
);
});
</script>
</head>
<body>
<div>
<table id="jqTable" class="scroll"></table>
<div id="jqTablePager" />
</div>
</body>
</html>
- The JavaScript and CSS files downloaded from the web are referenced in the beginning of the "Default.htm" file.
- The HTML "
table
" "jqTable
" and the HTML "div
" "jqTablePager
" are the HTML elements needed to generate the grid. - In the "
$(document).ready
" event, the JavaScript code calls the "jqGrid()
" function from the "jQuery Grid Plugin" to create the grid.
When we create the grid, we can pass many parameters to the "jqGrid()
" function through a "Json" object. In this example, I passed the following information to this function:
- The parameters for the "jQuery Grid Plugin" to issue "Ajax" calls. In this example, all the calls from the grid to the server will go to the action method "
LoadjqData
" in the "jQGrid
" controller. - The names of the columns in the grid.
- The configuration information for each column through the "
colModel
" parameter. - The information needed for the paging.
- By default, sorting is enabled for all the columns in the grid. We only need to specify the default sorting column and sorting order.
In the function call to "navGrid()
", we can further configure the behavior of the grid. For simplicity, I disabled the editing capabilities so we can focus on creating a read-only grid using the "jQuery Grid Plugin". By default, the search capability is enabled for the grid and the "jQuery Grid Plugin" provides us a long list of search operations. In this example, I will only demonstrate how to implement the "contains
" type of search by limiting the search options using the "sopt
" parameter.
The "jQGridController" Controller
The server code that sends the data to display in the grid is implemented in the "jQGridController.cs":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using jqGridExamplePart1.Models;
using System.Linq.Expressions;
namespace jqGridExamplePart1.Controllers
{
public class jQGridController : Controller
{
[HttpPost]
public ActionResult LoadjqData(string sidx, string sord, int page, int rows,
bool _search, string searchField, string searchOper, string searchString)
{
var students = StudentRepository.GetStudents().AsQueryable();
var filteredStudents = students;
if (_search)
{
filteredStudents = students.Where(s =>
(typeof(Student).GetProperty(searchField).GetValue
(s, null) == null) ? false :
typeof(Student).GetProperty(searchField).GetValue(s, null)
.ToString().Contains(searchString));
}
var sortedStudents = SortIQueryable<Student>(filteredStudents, sidx, sord);
var totalRecords = filteredStudents.Count();
var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);
var data = (from s in sortedStudents
select new
{
id = s.Id,
cell = new object[] { s.Id, s.Name,
s.Score, s.Enrollment.ToString("MM/dd/yyyy") }
}).ToArray();
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = data.Skip((page - 1) * rows).Take(rows)
};
return Json(jsonData);
}
private IQueryable<T> SortIQueryable<T>(IQueryable<T> data,
string fieldName, string sortOrder)
{
if (string.IsNullOrWhiteSpace(fieldName)) return data;
if (string.IsNullOrWhiteSpace(sortOrder)) return data;
var param = Expression.Parameter(typeof(T), "i");
Expression conversion = Expression.Convert
(Expression.Property(param, fieldName), typeof(object));
var mySortExpression = Expression.Lambda<Func<T, object>>(conversion, param);
return (sortOrder == "desc") ? data.OrderByDescending(mySortExpression)
: data.OrderBy(mySortExpression);
}
}
}
In this example, the "jQuery Grid Plugin" will make "Ajax" calls to the action method "LoadjqData
" to get the data to display in the grid. All the "Ajax" calls to the server are automatically initiated by the "jQuery Grid Plugin", we do not need to call the "$.ajax()
" method directly in our code to set up the grid. The "Ajax" calls will pass all the information that the server needs to prepare the data through the function parameters, such as the information required for sorting, paging, and searching. Using the information in the function parameters, the "LoadjqData
" method goes through the following steps to send the data to the grid:
- It first retrieves the whole list of students from the "
StudentRepository
". - If search is required, it will get a sub-set of the students based on the search criterion.
- It then sorts the filtered student list and calculate the total number of the pages needed to display the data for the given page size.
- At last, it prepares the data in the format that is recognized by the "jQuery Grid Plugin" and sends the data to the web browser in a "Json" object.
The "SortIQueryable
" method is a utility method that helps to sort the list of the students. My implementation of the "LoadjqData
" method is based on that the students are saved in memory and there is no "index" on the data. You do not need to implement it the same way if your data is stored in the database and the data is well indexed. You may take advantage of the indexes in your database to improve the speed. In practice, although not always, retrieving data from a well indexed database may prove faster than manipulating the data cached in the web server's memory.
Run the Application
Now we finish the implementation of a minimally functional grid, let us take a look at how it looks like in the web browser. You can debug run this example in your Visual Studio. When the application launches, the grid is shown in the browser. By default, the grid is sorted by the "Id
" column in ascending order.
If you click on the header of the "Id
" column, you can see that the sorting order is changed and the student with the largest "Id
" number is shown at the top.
To save some space for the "CodeProject", I am not going to post all the pictures when testing this grid. But if you run the application by yourself, you can test all the sorting, paging, and searching capabilities implemented in this example.
Points of Interest
- This is the part one of the article to present an example on how to use "jQuery Grid Plugin".
- When you finish reading this article, you should know the minimal set of JavaScript libraries, CSS styles, and images that you need to download to create a basic grid using the "jQuery Grid Plugin". You should also know how to implement the basic sorting, paging, and searching capabilities for the grid using an "MVC" controller.
- The "jQuery Grid Plugin" is a very flexible and powerful JavaScript library and you can create complex grids upon it. This article only shows you how to create a very simple grid to help you get started.
- I hope you like my postings and I hope this article can help you one way or the other.
History
- First revision - 7/29/2011