Introduction
In this article we will see how to create a GridView for our ASP.Net MVC application. All of you are aware of our ASP.NET GridView and this GridView is our favorite control to display data but when we use it in an ASP.NET MVC application we lose it; as you know MVC has actions and we can perform actions in the case of GridView in MVC. In this article we will see the alternate way of how we can create our GridView for ASP.Net MVC application.
To accomplish this task we need the j-query grid plug-in which you can download from here. First download this plug-in which contains only the js and css files. Using them we will create our GridView for the MVC application. In this article we will see a static GridView, populated from a database and a GriView with paging and sorting. So let's start to create our GridView.
Static GridView
In this GridView we will display the static records which we are creating to display in a grid so follow the steps given below.
Step 1:
Copy the following js and css files to your application in Scripts and content folder from downloaded plug-in files.
jquery-ui-1.8.7.css
ui.jqgrid.css
ui.multiselect.css
jquery-1.5.2.min.js
grid.locale-en.js
jquery.jqGrid.min.js
Step 2:
Provide the links to these files in the <head>section</head> of your view like below.
<link href="/Content/jquery-ui-1.8.7.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.multiselect.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/Js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/js/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/Js/jquery.jqGrid.min.js" type="text/javascript"></script>
Step 3:
Now write the script which will create our column header and pass the HTML table id as the id for the GridView like below.
<script type="text/javascript">
$(function () {
$("#list").jqGrid({
url: '/Home/StaticData/',//this is action in controller which returns the json as result.
datatype: 'json',
mtype: 'GET',
colNames: ['AuthorId', 'Author Name', 'Location'],//column name
colModel: [
{ name: 'AuthorId', index: 'Id', width: 40, align: 'left' },
{ name: 'Name', index: 'Name', width: 240, align: 'left' },
{ name: 'Location', index: 'Location', width: 200, align: 'left'}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
caption: 'Authors'
});
});
</script>
Step 4:
Now create your body part like below which contains a table with the id "list" and div tag with id "pager", because we use this id in the above script.
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
Step 5:
Now first, create the action in your controller with the name StaticData which returns json results like below.
public ActionResult StaticData(string sidx, string sord, int page, int rows)
{
int totalPages = 1;
int pageSize = rows;
int totalRecords = 3;
var jsonData = new { total = totalPages, page = page, records = totalRecords, rows = new[] {
new {id=1,cell=new[]{"100","Vulpes","India"}},
new {id=2,cell=new[]{"110","Sp Nayak","India"}},
new {id=3,cell=new[]{"120","Krishna Garad","India"}}
}
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
In the above line of code I created only three rows for my grid but you can increase these rows by creating additional records.
Step 6:
It's done; we have created our GridView to display the static data in the view; just run the application and see the result.
Still now we saw the GridView with static data, but in our application max we are required to pull the data from a database and display it in a grid. Next we will see how to populate a grid from a database.
Populate from DataBase
To create a GridView which shows the records from a database then first you need to add one Linq to SQL class in the models folder and fetch the entity which you want on the create class from the Server Explorer. Next you simply have to access the records from this class and prepare them as records for our GridView, so write one more action in your controller like below.
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
var context = new CSCAuthorsDataContext();
var jsonData = new
{
total=1,
page=page,
records=context.Authors.Count(),
rows=(from n in context.Authors
select new{i=n.AuthorId
,cell=new string[]{n.AuthorId.ToString(),n.Name.ToString(),n.Location.ToString()}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Then simply replace the script which we have written in our view in the head section, with this method name or action name. Where to replace I'd commented it in the above script. Now run your application and see the result.
Grid with Paging and Sorting
Still we have seen a simple grid and dynamic grid but if we try to make paging or sorting in the above sessions it is not possible but max we need to provide a paging facility and in our simple GridView we can not use in MVC application because we can handle the paging event of the grid in MVC so next we will provide the paging and sorting functionality to the above GridView by using dynamic linq. By using dynamic linq queries we can provide the paging, sorting, editing and updating for our j-query grid. Here we will provide only paging and sorting so write the following action in your controller.
public ActionResult PagingAndSorting(string sidx, string sord, int page, int rows)
{
var context = new CSCAuthorsDataContext();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = context.Authors.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var authors = context.Authors.OrderBy("AuthorId" + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (from n in authors
select new
{
i = n.AuthorId,
cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
In the above action on the start we have done some calculations like records, pages current record etc.. and then we have pulled the records using dynamic linq queries and simply returns the json result.
It's done; just replace the action name in the script on your view and now run your application and see the paging and sorting options are now working.
Conclusion
Using j-query we can create a simple grid for our ASP.Net MVC application.