Click here to Skip to main content
15,860,972 members
Articles / Web Development / HTML

An Example to Use jQuery Grid Plugin in MVC - Part 1

Rate me:
Please Sign up or sign in to vote.
4.70/5 (17 votes)
1 Aug 2011CPOL7 min read 221.9K   10.4K   71   33
This article presents a simple example on how to use jQuery Grid Plugin in MVC.

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

SolutionExplorer.jpg

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:

C#
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()
        {
            // Always re-direct to the "Default.htm" page
            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:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace jqGridExamplePart1.Models
{
    // The student class
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Score { get; set; }
        public DateTime Enrollment { get; set; }
    }
 
    // This static class serves as a repository of the student collection
    public static class StudentRepository
    {
        private static readonly List<Student> Students = new List<Student>();
        public static List<Student> GetStudents() { return Students; }
 
        // Static constructor to initiate some students in the repository
        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:

HTML
<!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">
    // the url to make the Ajax calls
    var jqDataUrl = "jQGrid/LoadjqData";
    $(document).ready(function () {
 
        // Set up the jquery grid
        $("#jqTable").jqGrid({
            // Ajax related configurations
            url: jqDataUrl,
            datatype: "json",
            mtype: "POST",
 
            // Specify the column names
            colNames: ["Id", "Name", "Score", "Enrollment"],
 
            // Configure the columns
            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"}],
 
            // Grid total width and height
            width: 550,
            height: 200,
 
            // Paging
            toppager: true,
            pager: $("#jqTablePager"),
            rowNum: 5,
            rowList: [5, 10, 20],
            viewrecords: true, // Specify if "total number of records" is displayed
            
            // Default sorting
            sortname: "Id",
            sortorder: "asc",
 
            // Grid caption
            caption: "A Basic jqGrid - Read Only"
        }).navGrid("#jqTablePager",
            { refresh: true, add: false, edit: false, del: false },
                {}, // settings for edit
                {}, // settings for add
                {}, // settings for delete
                {sopt: ["cn"]} // Search options. Some options can be set on column level
         );
    });
</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":

C#
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)
        {
            // Get the list of students
            var students = StudentRepository.GetStudents().AsQueryable();
 
            // If search, filter the list against the search condition.
            // Only "contains" search is implemented here.
            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));
            }
 
            // Sort the student list
            var sortedStudents = SortIQueryable<Student>(filteredStudents, sidx, sord);
 
            // Calculate the total number of pages
            var totalRecords = filteredStudents.Count();
            var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);
 
            // Prepare the data to fit the requirement of jQGrid
            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();
 
            // Send the data to the jQGrid
            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = data.Skip((page - 1) * rows).Take(rows)
            };
 
            return Json(jsonData);
        }
 
        // Utility method to sort IQueryable given a field name as "string"
        // May consider to put in a central place to be shared
        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.

RunAppStart.jpg

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.

RunAppSorting.jpg

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions

 
Questionpass search parameter Pin
Surender853-Mar-14 2:16
Surender853-Mar-14 2:16 
AnswerRe: pass search parameter Pin
Dr. Song Li3-Mar-14 2:48
Dr. Song Li3-Mar-14 2:48 
QuestionHow to use "jqGrid" with "setInterval" Pin
aSnoussi12-Jun-13 8:09
aSnoussi12-Jun-13 8:09 
QuestionRe: Edit, Add, Delete in JQuery Grid. Pin
Rohith Reddy Vadiyala31-Mar-13 20:01
Rohith Reddy Vadiyala31-Mar-13 20:01 
AnswerRe: Edit, Add, Delete in JQuery Grid. Pin
Dr. Song Li1-Apr-13 4:06
Dr. Song Li1-Apr-13 4:06 
GeneralRe: Edit, Add, Delete in JQuery Grid. Pin
Rohith Reddy Vadiyala2-Apr-13 18:56
Rohith Reddy Vadiyala2-Apr-13 18:56 
GeneralMy vote of 5 Pin
Jewel10013-Mar-13 0:37
Jewel10013-Mar-13 0:37 
GeneralRe: My vote of 5 Pin
Dr. Song Li13-Mar-13 3:52
Dr. Song Li13-Mar-13 3:52 
SuggestionjQuery grid plugin options Pin
Member 37365321-Jan-13 4:18
Member 37365321-Jan-13 4:18 
QuestionIssues Pin
sagar wasule13-Dec-12 18:51
sagar wasule13-Dec-12 18:51 
AnswerRe: Issues Pin
Dr. Song Li14-Dec-12 7:32
Dr. Song Li14-Dec-12 7:32 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey9-Aug-12 20:42
professionalManoj Kumar Choubey9-Aug-12 20:42 
Questionproblem in calling jquery function Pin
aakashmca18-Jul-12 23:49
aakashmca18-Jul-12 23:49 
QuestionAny MVC Grid Control? Pin
P_A_14-Jun-12 2:10
P_A_14-Jun-12 2:10 
Hi Song...

Instead of using the JQuery Grid, Can we use any MVC Control to display the data?

Is there any MVC Grid Control? ....Confused | :confused:
AnswerRe: Any MVC Grid Control? Pin
Dr. Song Li4-Jun-12 3:16
Dr. Song Li4-Jun-12 3:16 
GeneralBest article, My Vote 5 Pin
Kishor Shivane14-May-12 18:31
Kishor Shivane14-May-12 18:31 
GeneralMy vote of 5 Pin
lavsilva12-Mar-12 22:00
lavsilva12-Mar-12 22:00 
GeneralThanks Pin
jayendrasinh13-Dec-11 0:38
jayendrasinh13-Dec-11 0:38 
GeneralRe: Thanks Pin
Dr. Song Li13-Dec-11 5:43
Dr. Song Li13-Dec-11 5:43 
Questionset number of columns (4) Pin
newb710-Nov-11 10:08
newb710-Nov-11 10:08 
AnswerRe: set number of columns (4) Pin
Dr. Song Li10-Nov-11 11:47
Dr. Song Li10-Nov-11 11:47 
GeneralRe: set number of columns (4) Pin
newb710-Nov-11 14:14
newb710-Nov-11 14:14 
AnswerRe: set number of columns (4) Pin
Dr. Song Li10-Nov-11 14:27
Dr. Song Li10-Nov-11 14:27 
Questioncrud Pin
newb76-Nov-11 7:37
newb76-Nov-11 7:37 
AnswerRe: crud Pin
Dr. Song Li6-Nov-11 14:07
Dr. Song Li6-Nov-11 14:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.