Introduction
Let us see how to implement the jQuery DataTables with server-side custom filter searching, and IQueryable sorting and pagination in ASP.NET MVC 5 application. It’s always best to use a grid with server side processing for fast loading of grid list in application even with millions of data in a database table.
Background
jQuery DataTables is a plug-in for the Javascript library developed by Allan Jardine. It very flexible and easy to implement the tool, which will give you advanced interaction controls to any HTML tables.
Setup jQuery dataTables
Add the jQuery.DataTables from NuGet package manager and refer to the query.dataTables.min.js, dataTables.bootstrap.js and dataTables.bootstrap.css to your Layout.
Create Model
First, let us create the model for returning the data and displaying the values for the grid.
- using System.ComponentModel.DataAnnotations;
- namespace MVCApplication.Models
- {
- public class EmployeeDetails
- {
- public long Id { get; set; }
- public string EmpCode { get; set; }
- public string EmpName { get; set; }
- public string Gender { get; set; }
- }
- }
Create Controller and View
Now, let us create a controller and cshtml view for rendering the jQuery dataTable.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MVCApplication.Controllers
- {
- public class EmployeeDataController : Controller
- {
-
- [HttpGet]
- public ActionResult EmployeeDataList()
- {
- try
- {
- return View();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
I have created the ActionResult method EmployeeDataList inside the controller with HTTP get attribute. Now let’s create the EmployeeDataList.cstml view for the action result.
- @{
- ViewBag.Title = "Employee data";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- @section Styles{
- <style type="text/css">
- div.dataTables_filter {
- display: none !important;
- }
-
- table.dataTable tbody td {
- vertical-align: middle !important;
- padding: 5px !important;
- }
- </style>
- }
- <div class="row">
- <div class="col-md-12 col-sm-12 col-xs-12">
- <div class="table-responsive" style="background-color:#fff;font-size:13px;padding-top:5px;">
- <table id="Employeegrid" class="display dataTable cell-border table-bordered" style="width: 100%;" cellspacing="0">
- <thead>
- <tr>
- <th data-sortable="false">Id</th>
- <th>Emp Code</th>
- <th>Emp Name</th>
- <th>Gender</th>
- </tr>
- </thead>
- <thead class="filters" style="text-transform:uppercase;">
- <tr>
- <td style="padding:5px;">Emp Code</td>
- <td style="padding:5px;">Emp Name</td>
- <td style="padding:5px;">Gender</td>
- </tr>
- </thead>
- <tbody style="text-transform:uppercase;"></tbody>
- </table>
-
- </div>
- </div>
- </div>
The first <thead></thead> is for column header and the second is for the custom filter on column level. The next step is to populate the data on the grid using the Ajax call to server side. The below code snippet will do it.
- @section Scripts
- {
- <script type="text/javascript">
-
- $(document).ready(function () {
- $('#Employeegrid).dataTable({
- "paging": true,
- "ordering": true,
- "filter": true,
- "destroy": true,
- "orderMulti": false,
- "serverSide": true,
- "Processing": true,
- "columnDefs": [
- { "width": "5%", "targets": [0] }
- ],
- "ajax":
- {
- "url": "/EmployeeData/GetEmployeeDataList",
- "type": "POST",
- "dataType": "JSON"
- },
- "aoColumns": [
- {
- "mDataProp": "Id",
- "visible": false
- },
- {"mDataProp": "EmpCode"},
- {"mDataProp": "EmpName"},
- {"mDataProp": "Gender"}
- ]
- });
-
-
- $('#Employeegrid.filters td').each(function () {
-
- var title = $('# Employeegrid thead td').eq($(this).index()).text();
- if (title) {
- $(this).html('<input type="text" class="form-control" />');
- }
- });
-
-
- var table = $('#Employeegrid').DataTable(
- {
- "bFilter": true,
- "order": []
- });
-
-
- var delay = (function () {
- var timer = 0;
- return function (callback, ms) {
- clearTimeout(timer);
- timer = setTimeout(callback, ms);
- };
- })();
-
-
-
- table.columns().eq(0).each(function (colIdx) {
- $('input', $('.filters td')[colIdx]).bind('keyup', function () {
- var coltext = this.value;
- var colindex = colIdx;
- delay(function () {
- table
- .column(colindex)
- .search(coltext)
- .draw();
- }, 500);
- });
- });
- });
- </script>
- }
Next, let create a post ActionResult method to get the data from database and populate in the jQuery dataTable.
- public ActionResult GetEmployeeDataList()
- {
- try
- {
- string draw = Request.Form.GetValues("draw")[0];
- string order = Request.Form.GetValues("order[0][column]")[0];
- string orderDir = Request.Form.GetValues("order[0][dir]")[0];
- int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
- int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
-
-
- string EmpCode = Request.Form.GetValues("columns[0][search][value]").FirstOrDefault();
- string EmpName = Request.Form.GetValues("columns[1][search][value]").FirstOrDefault();
- string Gender = Request.Form.GetValues("columns[2][search][value]").FirstOrDefault();
-
- IQueryable<Employee> employee = DbContext.Employee;
-
-
- long TotalRecordsCount = employee.count();
-
-
-
- #region filters
-
- if (!string.IsNullOrEmpty(EmpCode) && !string.IsNullOrWhiteSpace(EmpCode))
- {
- employee = employee.Where(x => x.Code != null && x. Code.ToLower().Contains(EmpCode.ToLower()));
- }
- if (!string.IsNullOrEmpty(EmpName) && !string.IsNullOrWhiteSpace(EmpName))
- {
- employee = employee.Where(x => x.Name != null && x.Name.ToLower().Contains(EmpName.ToLower()));
- }
- if (!string.IsNullOrEmpty(Gender) && !string.IsNullOrWhiteSpace(Gender))
- {
- employee = employee.Where(x => x.Gender != null && x.Gender.ToLower().Contains(Gender.ToLower()));
- }
- #endregion
-
-
-
- long FilteredRecordCount = employee.Count();
-
-
-
- #region Sorting
-
-
- switch (order)
- {
- case "1":
- employee = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? employee.OrderByDescending(p => p.Code) : employee.OrderBy(p => p.Code);
- break;
- case "2":
- employee = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? employee.OrderByDescending(p => p.Name) : employee.OrderBy(p => p.Name);
- break;
- case "3":
- employee = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? employee.OrderByDescending(p => p.Gender) : employee.OrderBy(p => p.Gender);
- break;
- default:
- employee = employee.OrderByDescending(p => p.Id);
- break;
-
- #endregion
-
- var listemployee = employee.Skip(startRec).Take(pageSize).ToList()
- .Select(d => new EmployeeDetails()
- {
- Id = d.Id,
- EmpCode = d.Code,
- EmpName = d.Name,
- Gender = d.Gender
- }).ToList();
-
-
- if (listemployee == null)
- listemployee = new List<EmployeeDetails>();
-
-
- return this.Json(new
- {
- draw = Convert.ToInt32(draw),
- recordsTotal = TotalRecordsCount,
- recordsFiltered = FilteredRecordCount,
- data = listemployee
- }, JsonRequestBehavior.AllowGet);
- }
- catch (Exception ex)
- {
- throw;
- }
- }
So, we have to finished all the steps to build the server side processing with jquery DataTables in MVC application. I hope this will help you out.