Web Tutorials

HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
.NET Tutorial
PHP Tutorial

Interview Q & A

ASP.NET Q & A
WEB API Q & A
WCF Q & A
JQuery Q & A
MVC Q & A
Bootstrap Q & A
LINQ Q & A
AJAX Q & A
SQL Server Q & A
C# Q & A
OOPS Q & A

Code Examples

AngularJS
Google MAP API V3
ASP.NET

Utility Tools

Html Encode
Html Decode
URL Decode
URL Encode
Base64 Encode
Base64 Decode
JSON Beautifier

JQGrid in ASP.NET MVC 5 With Razor View And Entity Framework 6

Posted By: Ajay Saptaputre, 13 Oct,2015  |  Total View : 30134

In my previous article I discussed about create CRUD operation using Scaffolding with ASP.NET MVC 5 and database first approach using ASP.NET MVC 5 and Entity Framework 6 and model first approach using ASP.NET MVC 5 and Entity Framework 6

In this article I will discuss how to create dynamic JSON data from controller and bind server side data to the JQGrid.

What is JQGrid?

JQGrid was developed by Tony Tomov at Trirand Inc. JQGrid is a plug-in and work with the help of JQuery library. JQGrid is Ajax based JavaScript control that provides data presentation and data manipulation in tabular format for web application. JQGrid loaded data dynamically using Ajax call can work with any server side technology, including ASP.NET, MVC, JAVA, PHP etc. So JQGrid can be used to fill data from almost any web service providing data in JSON or XML format. For your information, Trirand also develops commercially-available, server-side grid components for PHP and ASP.NET.

ASP.NET MVC does not have any built in data binding controls like GridView, DetailsView etc. JQGrid provides similar functionality like other data binding controls provides like sorting, paging, ordering, column formatting etc. JQGrid makes developers life easy and saves there time rather he has to write code to display data in tabular manner.

Features of JQGrid

  • JQGrid support any server side technology, including ASP.NET, MVC, JAVA, PHP etc.
  • JQGrid can be used to fill data from almost any web service providing data in JSON or XML format.
  • The new rendering engine is 5-10 times faster loading speed then the previous.
  • JQGrid support inline Editing: easy to update the cell content in a particular row.
  • JQGrid support searching and filtering.
  • JQGrid support pagination functionality.
  • JQGrid support sorting, various data types and sub grid support functionality.
  • JQGrid support import and export data.
  • JQGrid is flexible to change the grid skin by defining their own UI CSS framework.
  • JQGrid support cross browser functionality.

So let's open Visual Studio and start creating new empty ASP.NET MVC5 application. In this article I am using Visual Studio Express 2013 for Web but you can use Visual Studio 2013 as well.

Now start creating ASP.NET Web project in Visual Studio 2013.

Create Model using Entity Framework 6

In order to start our sample application we will need database table, entity and DBContect classes to fetch the data from database. In this article I am not covering steps those are already covered in my previous article. If you did not read, please refer database first approach using ASP.NET MVC 5 and Entity Framework 6 and follow Step 1 to Step 16 it will help you to understand this article.

Install Jquery.JqGrid

Before going to start, we will need to add "Jquery.JqGrid" packages that will help us to display data in Grid format. All right, right click on project or go to "Tool" menu and select "Library Package Manager" and then select "Manage NuGet Package for Solution..." option. Now, search for "Jquery.JqGrid" and select "Jquery.JqGrid" from list and clicks on "Install" button. See below screen shot:


Add Empty Controller

I hope you already red my previous article. Now, right click on Controller folder and select Controller from menu as below screen shot. Now select MVC 5 empty controller, rename controller name as "EmployeeController". Click on "Add" button.



Add Code to the Controller

Now add below code to the controller class. The below code will send JSON array of "Employee" object to the view. In below code snippet, you can see the "getEmployees" method returning "JsonResult" as result. The result includes, total, page, records and rows as list of employees.

using MVCJQGrid.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCJQGrid.Controllers
{
    public class MVCJQGridController : Controller
    {
        MVCJQGridModel db = new MVCJQGridModel();
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public JsonResult getEmployees()
        {
            var jsonData = new
            {
                total = 1,
                page = 1,
                records = db.Employees.ToList().Count,
                rows = (
                  from emp in db.Employees.ToList()
                  select new
                  {
                      id = emp.id,
                      cell = new string[] { 
                      emp.Name.ToString(), 
                      emp.Designation.ToString(), 
                      emp.Gender.ToString(), 
                      emp.Salary.ToString(), 
                      emp.City, emp.State, 
                      emp.Zip.ToString()
                      }
                  }).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        } 
    }
}

Add Empty View

Now right click on "Index" action method, select "Add View" and select "Empty" template from dropdown.


Add Script References

Now we need to include ui.jqgrid.css, grid.locale-en.js, jquery.jqGrid.min.js files, do not miss JQuery reference in our project. Also, remember to remove other script references. All right, now include all files reference in "_Layout.cshtml" file under head section. As below code snippet:

<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
    <script src="~/Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>

Add JQGrid Code in View

To bind data to JQGrid is quite simple. You need to make Ajax call to your controller's "getEmployees" method, see above code snippet. This Ajax call gets JSON data from server and loading into the JQGrid control. Also, you can observer that I am setting some properties like "rowNum", "rowList", "sortname","viewrecords", "sortorder" etc. Here "colNames" array is used to display column captions for grid.

JQGrid also includes "colModel" array, where you need to specify actual model. Currently I am setting "false" for add, edit and delete functionality. You can see here I am using JQuery $(document).ready() function that will execute, once document is ready. The most important property is "url" where you need to specify controller and action method name. As given in below code snippet:

<script language="javascript">
$(document).ready(function () {
	$("#list2").jqGrid({
		url: 'https://localhost:49765/MVCJQGrid/getEmployees',
		datatype: "json",
		contentType: "application/json; charset-utf-8",
		mtype: 'GET',
		colNames: ['ID', 'Employee Name', 'Designation', 
		'Gender', 'Salary', 'City', 'State', 'Zip'],
		colModel: [
			{ name: 'id', index: 'id', width: 55, sorttype: "int" },
			{ name: 'Name', index: 'Name', width: 90 },
			{ name: 'Designation', index: 'Designation', width: 100 },
			{ name: 'Gender', index: 'Gender', width: 80 },
			{ name: 'Salary', index: 'Salary', width: 80, 
					align: "right", sorttype: "float" },
			{ name: 'City', index: 'City', width: 80 },
			{ name: 'State', index: 'State', width: 150 },
			{ name: 'Zip', index: 'Zip', width: 150 }
		],
		rowNum: 5,
		rowList: [5, 10, 15],
		pager: '#pager2',
		sortname: 'id',
		viewrecords: true,
		sortorder: "asc",
		caption: "JSON Example"
	});
	jQuery("#list2").jqGrid('navGrid', '#pager2', 
		{ edit: false, add: false, del: false });
});
</script>

Run ASP.NET MVC Application

Now our sample ASP.NET web application is ready to run. Press Ctrl + F5 and run the application, you can see below output in browser.


Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

Download Code ⇩