ASP.NET MVC jQuery Server Side Datatable Example

Introduction

 
Today I will demonstrate the implementation of jQuery server side Datatable in MVC appplication with server side filter, sorting and Pagination.
 
Datatable is a jQuery plugin to display data in tabular format with sorting, filter and pagination written in javascript. Datatable is a flexible tool which allows the customization of the plugin as per our requirement.
 
Today we will create an MVC application which will be using Datatable plugin with searching, sorting, pagination functionality. 
 
Prequisites 
 
Basic knowledge of MVC application (Controller, Action and Views)  jQuery and Ajax.
 
Step 1 
 
Create a basic Web Application with MVC framework, build it and launch the application once to check whether everything is configured properly or not.
 
Step 2
 
We will create a simple table to display employee detail in datatable. First of all create a new controller (EmployeeController) in your Application.
and create a view for Action Index named as Index.cshtml.
 
Step 3
 
Import the CDN (Content Delivery Network) or download the required css and js file. Here I am using CDN for required js and css. 
 
Imported css 
 
Import below css in your view Index.cshtml,
  1. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />    
  2. <link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />    
Imported javascript
 
Import below js in your view Index.cshtml
  1. <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>    
  2. <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>    
Step 4
 
Create Model to bind the request data. Create a class file named as JqueryDatatableParam and paste the code as below.
  1. public class JqueryDatatableParam    
  2. {    
  3.         public string sEcho { getset; }    
  4.         public string sSearch { getset; }    
  5.         public int iDisplayLength { getset; }    
  6.         public int iDisplayStart { getset; }    
  7.         public int iColumns { getset; }    
  8.         public int iSortCol_0 { getset; }    
  9.         public string sSortDir_0 { getset; }    
  10.         public int iSortingCols { getset; }    
  11.         public string sColumns { getset; }    
  12.  }    
Step 5
 
Create Model to bind the request data. Create a class file named as Employee and paste the code as below. 
  1. public class Employee    
  2.     {    
  3.         public string Name { getset; }    
  4.         public string Position { getset; }    
  5.         public string Location { getset; }    
  6.         public int Age { getset; }    
  7.         public DateTime StartDate { getset; }    
  8.         public string StartDateString { getset; }    
  9.         public int  Salary { getset; }    
  10.     }    
Step 6
 
We will create an action method to in our EmployeeController to return the data which we will display in view.
 
Create a method named GetData in EmployeeController as below.
  1. public ActionResult GetData(JqueryDatatableParam param)    
  2. {    
  3.        var employees = GetEmployees(); //This method is returning the IEnumerable employee from database    
  4. }    
Filter
 
Add the following code in GetData method to apply server side filter.
  1. if (!string.IsNullOrEmpty(param.sSearch))    
  2.           {    
  3.               employeesemployees = employees.Where(x => x.Name.ToLower().Contains(param.sSearch.ToLower())    
  4.                                             || x.Position.ToLower().Contains(param.sSearch.ToLower())    
  5.                                             || x.Location.ToLower().Contains(param.sSearch.ToLower())    
  6.                                             || x.Salary.ToString().Contains(param.sSearch.ToLower())    
  7.                                             || x.Age.ToString().Contains(param.sSearch.ToLower())    
  8.                                             || x.StartDate.ToString("dd'/'MM'/'yyyy").ToLower().Contains(param.sSearch.ToLower())).ToList();    
  9.           }    
From html page whatever keyword we are typing in search textbox is sent to request in querystring as `sSearch` name. In the above code snippet we are checking if the same parameter `sSearch` is not null then we are checking the same keyword in our list to apply filter.
 
Note
To ignore case sensitive search before comparing we are converting the string to lower case.
 
Sorting
 
To apply Sorting add the following code in same GetData method. 
  1. var sortColumnIndex = Convert.ToInt32(HttpContext.Request.QueryString["iSortCol_0"]);  
  2. var sortDirection = HttpContext.Request.QueryString["sSortDir_0"];  
  3. if (sortColumnIndex == 3) {  
  4.     employees = sortDirection == "asc" ? employees.OrderBy(c => c.Age) : employees.OrderByDescending(c => c.Age);  
  5. else if (sortColumnIndex == 4) {  
  6.     employees = sortDirection == "asc" ? employees.OrderBy(c => c.StartDate) : employees.OrderByDescending(c => c.StartDate);  
  7. else if (sortColumnIndex == 5) {  
  8.     employees = sortDirection == "asc" ? employees.OrderBy(c => c.Salary) : employees.OrderByDescending(c => c.Salary);  
  9. else {  
  10.     Func < Employee, string > orderingFunction = e => sortColumnIndex == 0 ? e.Name : sortColumnIndex == 1 ? e.Position : e.Location;  
  11.     employees = sortDirection == "asc" ? employees.OrderBy(orderingFunction) : employees.OrderByDescending(orderingFunction);  
  12. }  
To apply sorting we required two parameters, Sorting direction (Ascendening or descding) and SortColumnName.  We are storing the sortdirection value in variable `sortDirection` and sortcolumn no in variable `sortColumnIndex`. And based on sortColumnIndex we are sorting the list.
 
Pagination
 
To apply the pagination add the below code in GetData() method. 
  1. var displayResult = employees.Skip(param.iDisplayStart)    
  2.                .Take(param.iDisplayLength).ToList();    
  3.            var totalRecords = employees.Count();   
For pagination also we require two value page numbers and count to display in per page. PageNumber is bound in `iDisplayStart` parameter and per page count is bound in `iDisplayLength` request parameter. And we are using the Take() and Skip() method of linq to perform the pagination based on value of both parameters.
 
Now add the below code snippet to send filtered and sorted data as response of ajax call in json format.
  1. return Json(new    
  2.            {    
  3.                param.sEcho,    
  4.                iTotalRecords = totalRecords,    
  5.                iTotalDisplayRecords = totalRecords,    
  6.                aaData = displayResult    
  7.            }, JsonRequestBehavior.AllowGet);    
Step 6
 
We have completed our method to perform all operations. Now we have to call this method from view and we have to bind all column values in table. Add the below code snippet in Index.cshtml page.
  1. <script>  
  2.        $(document).ready(function () {  
  3.            bindDatatable();  
  4.        });  
  5.   
  6.        function bindDatatable() {  
  7.            datatable = $('#tblStudent')  
  8.                .DataTable({  
  9.                    "sAjaxSource""/Employee/GetData",  
  10.                    "bServerSide"true,  
  11.                    "bProcessing"true,  
  12.                    "bSearchable"true,  
  13.                    "order": [[1, 'asc']],  
  14.                    "language": {  
  15.                        "emptyTable""No record found.",  
  16.                        "processing":  
  17.                            '<i class="fa fa-spinner fa-spin fa-3x fa-fw" style="color:#2a2b2b;"></i><span class="sr-only">Loading...</span> '  
  18.                    },  
  19.                    "columns": [  
  20.                        {  
  21.                            "data""Name",  
  22.                            "autoWidth"true,  
  23.                            "searchable"true  
  24.                        },  
  25.                        {  
  26.                            "data""Position",  
  27.                            "autoWidth"true,  
  28.                            "searchable"true  
  29.                        },  
  30.                        {  
  31.                            "data""Location",  
  32.                            "autoWidth"true,  
  33.                            "searchable"true  
  34.                        },  
  35.                        {  
  36.                            "data""Age",  
  37.                            "autoWidth"true,  
  38.                            "searchable"true  
  39.                        }, {  
  40.                            "data""StartDateString",  
  41.                            "autoWidth"true,  
  42.                            "searchable"true  
  43.                        }, {  
  44.                            "data""Salary",  
  45.                            "autoWidth"true,  
  46.                            "searchable"true  
  47.                        },  
  48.                    ]  
  49.                });  
  50.        }  
  51.    </script>  
In the above code snippet we are calling function bindDatatable() on document ready method. and we have defined the bindDatatable method as well.
 
To convert table to datatable we can use below code snippet based on table id. 
  1. $('#tblStudent').DataTable();   //tblStudent is the id of table rendered in dom
Description of other properties that we have set are as below.
  • AjaxSource : This attribute is used to set the url to make ajax call for fetching data. Here we have provided the url to call our method GetData from emloyeeController created in step 5.
  • ServerSide : This attribute is used to set the value whether datatable is server side or client side.
  • order : This attribute is used to set the default order value (i.e SortColumnName and SortDirection)
  • columns : This attribute is used to bind all columns.
The full code snippet of both files is as below 
 
Index.Cshtml 
  1. <h2>Index</h2>  
  2. @section styles{  
  3.     <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />  
  4.     <link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
  5. }  
  6. <div class="row">  
  7.     <div class="col-sm-12">  
  8.         <table class="table table-bordered table-striped" id="tblStudent">  
  9.             <thead>  
  10.                 <tr>  
  11.                     <th scope="col">Name</th>  
  12.                     <th scope="col">Position</th>  
  13.                     <th scope="col">Location</th>  
  14.                     <th scope="col">Age</th>  
  15.                     <th scope="col">Start Date</th>  
  16.                     <th scope="col">Salary</th>  
  17.                 </tr>  
  18.             </thead>  
  19.         </table>  
  20.     </div>  
  21. </div>  
  22.   
  23. @section scripts{  
  24.     <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>  
  25.     <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>  
  26.     <script>  
  27.         $(document).ready(function () {  
  28.             bindDatatable();  
  29.         });  
  30.   
  31.         function bindDatatable() {  
  32.             datatable = $('#tblStudent')  
  33.                 .DataTable({  
  34.                     "sAjaxSource""/Employee/GetData",  
  35.                     "bServerSide"true,  
  36.                     "bProcessing"true,  
  37.                     "bSearchable"true,  
  38.                     "order": [[1, 'asc']],  
  39.                     "language": {  
  40.                         "emptyTable""No record found.",  
  41.                         "processing":  
  42.                             '<i class="fa fa-spinner fa-spin fa-3x fa-fw" style="color:#2a2b2b;"></i><span class="sr-only">Loading...</span> '  
  43.                     },  
  44.                     "columns": [  
  45.                         {  
  46.                             "data""Name",  
  47.                             "autoWidth"true,  
  48.                             "searchable"true  
  49.                         },  
  50.                         {  
  51.                             "data""Position",  
  52.                             "autoWidth"true,  
  53.                             "searchable"true  
  54.                         },  
  55.                         {  
  56.                             "data""Location",  
  57.                             "autoWidth"true,  
  58.                             "searchable"true  
  59.                         },  
  60.                         {  
  61.                             "data""Age",  
  62.                             "autoWidth"true,  
  63.                             "searchable"true  
  64.                         }, {  
  65.                             "data""StartDateString",  
  66.                             "autoWidth"true,  
  67.                             "searchable"true  
  68.                         }, {  
  69.                             "data""Salary",  
  70.                             "autoWidth"true,  
  71.                             "searchable"true  
  72.                         },  
  73.                     ]  
  74.                 });  
  75.         }  
  76.     </script>  
  77. }  
 EmployeeController.cs
  1. public class EmployeeController : Controller  
  2.     {  
  3.         // GET: Student  
  4.         public ActionResult Index()  
  5.         {  
  6.             return View();  
  7.         }  
  8.   
  9.         public ActionResult GetData(JqueryDatatableParam param)  
  10.         {  
  11.             var employees = GetEmployees();  
  12.   
  13.             employees.ToList().ForEach(x => x.StartDateString = x.StartDate.ToString("dd'/'MM'/'yyyy"));  
  14.   
  15.             if (!string.IsNullOrEmpty(param.sSearch))  
  16.             {  
  17.                 employees = employees.Where(x => x.Name.ToLower().Contains(param.sSearch.ToLower())  
  18.                                               || x.Position.ToLower().Contains(param.sSearch.ToLower())  
  19.                                               || x.Location.ToLower().Contains(param.sSearch.ToLower())  
  20.                                               || x.Salary.ToString().Contains(param.sSearch.ToLower())  
  21.                                               || x.Age.ToString().Contains(param.sSearch.ToLower())  
  22.                                               || x.StartDate.ToString("dd'/'MM'/'yyyy").ToLower().Contains(param.sSearch.ToLower())).ToList();  
  23.             }  
  24.   
  25.             var sortColumnIndex = Convert.ToInt32(HttpContext.Request.QueryString["iSortCol_0"]);  
  26.             var sortDirection = HttpContext.Request.QueryString["sSortDir_0"];  
  27.   
  28.             if (sortColumnIndex == 3)  
  29.             {  
  30.                 employees = sortDirection == "asc" ? employees.OrderBy(c => c.Age) : employees.OrderByDescending(c => c.Age);  
  31.             }  
  32.             else if (sortColumnIndex == 4)  
  33.             {  
  34.                 employees = sortDirection == "asc" ? employees.OrderBy(c => c.StartDate) : employees.OrderByDescending(c => c.StartDate);  
  35.             }  
  36.             else if (sortColumnIndex == 5)  
  37.             {  
  38.                 employees = sortDirection == "asc" ? employees.OrderBy(c => c.Salary) : employees.OrderByDescending(c => c.Salary);  
  39.             }  
  40.             else  
  41.             {  
  42.                 Func<Employee, string> orderingFunction = e => sortColumnIndex == 0 ? e.Name :  
  43.                                                                sortColumnIndex == 1 ? e.Position :  
  44.                                                                e.Location ;  
  45.   
  46.                 employees = sortDirection == "asc" ? employees.OrderBy(orderingFunction) : employees.OrderByDescending(orderingFunction);  
  47.             }  
  48.   
  49.             var displayResult = employees.Skip(param.iDisplayStart)  
  50.                 .Take(param.iDisplayLength).ToList();  
  51.             var totalRecords = employees.Count();  
  52.   
  53.             return Json(new  
  54.             {  
  55.                 param.sEcho,  
  56.                 iTotalRecords = totalRecords,  
  57.                 iTotalDisplayRecords = totalRecords,  
  58.                 aaData = displayResult  
  59.             }, JsonRequestBehavior.AllowGet);  
  60.   
  61.         }  
  62. }  
 Now launch the application and go to the url `Employee/Index`  and you will get the following output.
 
ASP.NET MVC jQuery Server Side Datatable Example
 
Thanks for reading my article, please llet me know your feedback.