Introduction
In this article, we will see how to create a GridView for our ASP.Net MVC application. All of you are aware that our ASP.NET GridView 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 the 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 that 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 the Scripts and Content folder from the 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 that 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, we now see 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 that shows the records from a database then, you first need to add one Linq to the SQL class in the model's folder and fetch the entity that you want in the created 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 the one 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 max we need to provide a paging facility, and in our simple GridView, we can not use it in the 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 jquery 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, at the start, we did some calculations like records, page current records, etc. Then, we pulled the records using dynamic LINQ queries and simply returned the JSON result.
It's done; just replace the action name in the script on your view, 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.