Using DataTables Grid With ASP.NET MVC

Link to download Source Code.

ASP.NET

What is DataTables?

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.

Referenced from - https://datatables.net/

Pre prerequisite for Application

  1. Visual Studio 2012 / 2013 / 2015 / 2017
  2. Entity Framework 5 and above
  3. SQL Server 2008

Let’s start with database part first.

Database Part

I have created a database with the name “Northwind” and in that, it has “Customers” table.

ASP.NET

Next, we are going to create an ASP.NET MVC5 Web application.

Creating ASP.NET MVC5 Web Application

Open New Visual Studio 2015 IDE.

ASP.NET

After opening IDE just, next we are going to create MVC project for doing that just click File - inside that New - Project.

ASP.NET

After choosing a project, a new dialog will pop up with the name “New Project”. In that, we are going to choose Visual C# Project Templates - Web - ASP.NET Web Application. Then, we are going to name the project as “DemoDatatables”.

ASP.NET

After naming the project we are going click on OK button to create a project.

A new dialog will pop up for choosing templates for Creating “ASP.NET Web Application;” in that template, we are going to Create MVC application. That's why we are going to choose “MVC template” and next click on OK button to create a project.

ASP.NET

After clicking on OK button it will start to create a project.

Project Structure

ASP.NET

After creating project next, we are going to create Model.

Creating Customer Model

We are going to add Customer Model to the Models folder.

ASP.NET

Code Snippet

  1. [Table("Customers")]  
  2. public class Customers  
  3. {  
  4.     [Key]  
  5.     public int? CustomerID { get; set; }  
  6.     [Required(ErrorMessage = "Required CompanyName")]  
  7.     public string CompanyName { get; set; }  
  8.     [Required(ErrorMessage = "Required ContactName")]  
  9.     public string ContactName { get; set; }  
  10.     [Required(ErrorMessage = "Required ContactTitle")]  
  11.     public string ContactTitle { get; set; }  
  12.     public string Address { get; set; }  
  13.   
  14.     [Required(ErrorMessage = "Required City")]  
  15.     public string City { get; set; }  
  16.     public string Region { get; set; }  
  17.   
  18.     [Required(ErrorMessage = "Required PostalCode")]  
  19.     public string PostalCode { get; set; }  
  20.   
  21.     [Required(ErrorMessage = "Required Country")]  
  22.     public string Country { get; set; }  
  23.   
  24.     [Required(ErrorMessage = "Required Phone")]  
  25.     public string Phone { get; set; }  
  26.     public string Fax { get; set; }  
  27. }  

After adding model next, we are going to use Entity framework for accessing database to doing that we need to setup DbContext class.

Note - What is DbContext?

DbContext is an important part of Entity Framework.

It is a bridge between your domain or entity classes and the database.

DbContext is the primary class that is responsible for interacting with data as an object.

Referenced from here.

Setting up DbContext Class

In this part, we are first going to create a class with name “DatabaseContext” and this class will be inheriting from “DbContext” class.

We are going create this class in Model Folder.

ASP.NET

Note
“DBConnection” is Connection string name.

Note - What is DBSet?

Referenced from here.

DBSet class represents an entity set that is used for creating, read, update, and delete operations. A generic version of DBSet (DbSet<TEntity>) can be used when the type of entity is not known at build time.

After adding “DatabaseContext” class next we are going to inherit this class with “DbContext” class.

After inheriting class next in constructor we are going to create a connection for doing that we need to pass connection string name to “DbContext” class, we are passing connection string name as DBConnection.

After passing connection string next we are going to declare DbSet in “DbContext” class which will help us to perform create, read, update, and delete operations.

Code Snippet

  1. namespace DemoDatatables.Models  
  2. {  
  3.     public class DatabaseContext : DbContext  
  4.     {  
  5.         public DatabaseContext() : base("DBConnection")  
  6.         {  
  7.   
  8.         }  
  9.         public DbSet<Customers> Customers {get; set;}  
  10.     }  
  11.   
  12. }  

Connection string in Web.config file

  1. <connectionStrings>  
  2. <addname="DBConnection"  
  3. connectionString="Data Source=####; initial catalog=Northwind; user id=sa; password=Pass####;"  
  4. providerName="System.Data.SqlClient" />  
  5. </connectionStrings>  

Next, we are going to add a controller.

Adding DemoController

In this part, we are going to add a new controller with the name “Demo”.

ASP.NET

After we have clicked on Add button, it has created DemoController in Controller folder, as shown in the below view.

ASP.NET

After adding DemoController next we are going to download DataTables Scripts and add it to project.

Getting DataTables Scripts

The following Javascript library files are used in this example,

  • http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
  • https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js
  • https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js

The following CSS files are used in this example,

Bootstrap v3.3.7

https://getbootstrap.com/docs/3.3/getting-started/

DataTables CSS files

 

  • https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css
  • https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css

 

After completing with downloading script and css next we are going to add ShowGrid Action Method in DemoController.

Adding ShowGrid Action Method in Demo Controller

ASP.NET

After adding Action Method now let add View with name “ShowGrid”.

ASP.NET

Adding DataTables Grid Scripts and Css on ShowGrid View

In first step we are going to add Script and Css reference.

  1. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  2. <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  3.   
  4. <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
  5. <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />  
  6.   
  7. <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>  
  8. <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  

After adding Script and CSS reference next we are going to add DataTables Markup.

Adding DataTables Markup

It is simple Html Table in that we are going to add columns headers (“<th>”) with all the columns names which we want to display on the grid.

After adding Markup next, we are going to add DataTables function to Create DataTables. 

  1. <div class="container">  
  2.         <br />  
  3.         <div style="width:90%; margin:0 auto;">  
  4.             <table id="demoGrid" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">  
  5.                 <thead>  
  6.               <tr>  
  7.                 <th>CustomerID</th>  
  8.                 <th>CompanyName</th>      
  9.                 <th>ContactName</th>  
  10.                 <th>ContactTitle</th>  
  11.                 <th>City</th>  
  12.                 <th>PostalCode</th>  
  13.                 <th>Country</th>  
  14.                 <th>Phone</th>  
  15.                 <th>Edit</th>  
  16.                 <th>Delete</th>  
  17.             </tr>  
  18.                 </thead>  
  19.             </table>  
  20.         </div>  
  21.     </div>  

Adding DataTables Function to create DataTables

Code Snippet

  1. <script>  
  2.   
  3.     $('#demoGrid').dataTable({  
  4.     });  
  5. </script>  

DataTables Options

All definitions are taken from https://datatables.net website.

  • Processing - Enable or disable the display of a 'processing' indicator when the table is being processed (e.g. a sort).
  • server Side - Server-side processing - where filtering, paging, and sorting calculations are all performed by a server.
  • Filter - this option is used for enabling and disabling of search box
  • orderMulti - When ordering is enabled (ordering), by default DataTables allows users to sort multiple columns by shift-clicking upon the header cell for each column. Although this can be quite useful for users, it can also increase the complexity of the order, potentiality increasing the processing time of ordering the data. Therefore, this option is provided to allow this shift-click multiple column abilities
  • Ajax - Ajax request is made to get data to DataTables.
  • columnDefs - Set column definition initialisation properties.
  • Columns - Set column specific initialisation properties.

After completing with an understanding of options or properties next we are going to set it.

We are going to set “processing” option to true to display processing bar, after that, we are going to set the “serverSide” option to true because we are going to do paging and filtering at serverSide.

Next options after “serverSide” option are “filter.” We are going to use the search box; that's why we have set this property to true, “orderMulti” is also set to false because we do not want to sort multiple columns at once.

DataTables Options snapshot

ASP.NET

Ajax Option

And the main option is Ajax which we are going to use for calling an Action Method for getting data to bind DataTables Grid the data is in Json format. For that we are going to pass URL: -"/Demo/LoadData”, this request is Post request. And data type we are going to set as Json.

We are going to call LoadData Action Method which is under Demo Controller which I will explain in upcoming steps.

ASP.NET

columnDefs Option

After setting Ajax we have a “columnDefs” option which I have used for hiding Primary key of the table (“CustomerID”) and which should also be not searchable.

ASP.NET

columns Option

Finally, the second to last option is columns which are used for initialization of DataTables grid. Add that property which you need to render on the grid, which must be defined in this columns option.

ASP.NET

Render buttons in Columns

At last, we need to render button in the grid for editing data and deleting data.

ASP.NET

Finally, on click of the delete button, we can call a custom function to delete data as I have created “DeleteData” function.

Complete code Snippet of ShowGrid View

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7. <head>  
  8.     <meta name="viewport" content="width=device-width" />  
  9.     <title>ShowGrid</title>  
  10.     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  11.     <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  12.   
  13.     <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />  
  14.     <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />  
  15.   
  16.     <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>  
  17.     <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  
  18.   
  19.     <script>  
  20.         $(document).ready(function () {  
  21.             $("#demoGrid").DataTable({  
  22.   
  23.                 "processing"true// for show progress bar  
  24.                 "serverSide"true// for process server side  
  25.                 "filter"true// this is for disable filter (search box)  
  26.                 "orderMulti"false// for disable multiple column at once  
  27.                 "pageLength": 5,  
  28.   
  29.                 "ajax": {  
  30.                     "url""/Demo/LoadData",  
  31.                     "type""POST",  
  32.                     "datatype""json"  
  33.                 },  
  34.   
  35.                 "columnDefs":  
  36.                 [{  
  37.                     "targets": [0],  
  38.                     "visible"false,  
  39.                     "searchable"false  
  40.                 },  
  41.                 {  
  42.                     "targets": [7],  
  43.                     "searchable"false,  
  44.                     "orderable"false  
  45.                 },  
  46.                 {  
  47.                     "targets": [8],  
  48.                     "searchable"false,  
  49.                     "orderable"false  
  50.                 },  
  51.                 {  
  52.                     "targets": [9],  
  53.                     "searchable"false,  
  54.                     "orderable"false  
  55.                 }],  
  56.   
  57.                 "columns": [  
  58.                       { "data""CustomerID""name""CustomerID""autoWidth"true },  
  59.                       { "data""CompanyName""name""CompanyName""autoWidth"true },  
  60.                       { "data""ContactName""title""ContactName""name""ContactName""autoWidth"true },  
  61.                       { "data""ContactTitle""name""ContactTitle""autoWidth"true },  
  62.                       { "data""City""name""City""autoWidth"true },  
  63.                       { "data""PostalCode""name""PostalCode""autoWidth"true },  
  64.                       { "data""Country""name""Country""autoWidth"true },  
  65.                       { "data""Phone""name""Phone""title""Status""autoWidth"true },  
  66.                       {  
  67.                           "render"function (data, type, full, meta)  
  68.                           { return '<a class="btn btn-info" href="/Demo/Edit/' + full.CustomerID + '">Edit</a>'; }  
  69.                       },  
  70.                        {  
  71.                            data: null, render: function (data, type, row) {  
  72.                                return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>";  
  73.                            }  
  74.                        },  
  75.   
  76.                 ]  
  77.   
  78.             });  
  79.         });  
  80.     </script>  
  81.   
  82. </head>  
  83. <body>  
  84.     <div class="container">  
  85.         <br />  
  86.         <div style="width:90%; margin:0 auto;">  
  87.             <table id="demoGrid" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">  
  88.                 <thead>  
  89.                     <tr>  
  90.                         <th>CustomerID</th>  
  91.                         <th>CompanyName</th>  
  92.                         <th>ContactName</th>  
  93.                         <th>ContactTitle</th>  
  94.                         <th>City</th>  
  95.                         <th>PostalCode</th>  
  96.                         <th>Country</th>  
  97.                         <th>Phone</th>  
  98.                         <th>Edit</th>  
  99.                         <th>Delete</th>  
  100.                     </tr>  
  101.                 </thead>  
  102.             </table>  
  103.         </div>  
  104.     </div>  
  105. </body>  
  106. </html>  

After completing with initialization of DataTables grid next we are going to create LoadData Action Method.

Adding LoadData Action Method to Demo Controller

Here we are going to Add Action Method with name LoadData. In this action method, we are going to get all Customer records from the database to display and on the basis of the parameter we are going sort data, and do paging with data.

We are doing paging and filtering of data on the server side; that why we are using IQueryable which will execute queries with filters on the server side.

ASP.NET

For using OrderBy in the query we need to install System.Linq.Dynamic package from NuGet packages.

Snapshot while adding System.Linq.Dynamic package from NuGet packages

ASP.NET

After adding the package, next, we see the complete code snippet and how to get data and do paging and filtering with it.

Complete code Snippet of LoadData Action Method

All processes are step by step with comments; so it's easy to understand.

All Request.Form.GetValues parameters value will get populated when AJAX post method gets called on a load of if you do paging or sorting and search.

Code Snippet

  1. public ActionResult LoadData()  
  2. {  
  3.     try  
  4.     {  
  5.         var draw = Request.Form.GetValues("draw").FirstOrDefault();  
  6.         var start = Request.Form.GetValues("start").FirstOrDefault();  
  7.         var length = Request.Form.GetValues("length").FirstOrDefault();  
  8.         var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();  
  9.         var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();  
  10.         var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();  
  11.   
  12.   
  13.         //Paging Size (10,20,50,100)    
  14.         int pageSize = length != null ? Convert.ToInt32(length) : 0;  
  15.         int skip = start != null ? Convert.ToInt32(start) : 0;  
  16.         int recordsTotal = 0;  
  17.   
  18.         // Getting all Customer data    
  19.         var customerData = (from tempcustomer in _context.Customers  
  20.                             select tempcustomer);  
  21.   
  22.         //Sorting    
  23.         if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))  
  24.         {  
  25.             customerData = customerData.OrderBy(sortColumn + " " + sortColumnDir);  
  26.         }  
  27.         //Search    
  28.         if (!string.IsNullOrEmpty(searchValue))  
  29.         {  
  30.             customerData = customerData.Where(m => m.CompanyName == searchValue);  
  31.         }  
  32.   
  33.         //total number of rows count     
  34.         recordsTotal = customerData.Count();  
  35.         //Paging     
  36.         var data = customerData.Skip(skip).Take(pageSize).ToList();  
  37.         //Returning Json Data    
  38.         return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });  
  39.   
  40.     }  
  41.     catch (Exception)  
  42.     {  
  43.         throw;  
  44.     }  
  45.   
  46. }  

Complete code Snippet of DemoController

  1. using DemoDatatables.Models;  
  2. using System;  
  3. using System.Linq;  
  4. using System.Web.Mvc;  
  5. using System.Linq.Dynamic;  
  6. using System.Data.Entity;  
  7.   
  8. namespace DemoDatatables.Controllers  
  9. {  
  10.     public class DemoController : Controller  
  11.     {  
  12.         // GET: Demo  
  13.         public ActionResult ShowGrid()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         public ActionResult LoadData()  
  19.         {  
  20.             try  
  21.             {  
  22.                 //Creating instance of DatabaseContext class  
  23.                 using (DatabaseContext _context = new DatabaseContext())  
  24.                 {  
  25.                     var draw = Request.Form.GetValues("draw").FirstOrDefault();  
  26.                     var start = Request.Form.GetValues("start").FirstOrDefault();  
  27.                     var length = Request.Form.GetValues("length").FirstOrDefault();  
  28.                     var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();  
  29.                     var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();  
  30.                     var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();  
  31.   
  32.   
  33.                     //Paging Size (10,20,50,100)    
  34.                     int pageSize = length != null ? Convert.ToInt32(length) : 0;  
  35.                     int skip = start != null ? Convert.ToInt32(start) : 0;  
  36.                     int recordsTotal = 0;  
  37.   
  38.                     // Getting all Customer data    
  39.                     var customerData = (from tempcustomer in _context.Customers  
  40.                                         select tempcustomer);  
  41.   
  42.                     //Sorting    
  43.                     if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))  
  44.                     {  
  45.                         customerData = customerData.OrderBy(sortColumn + " " + sortColumnDir);  
  46.                     }  
  47.                     //Search    
  48.                     if (!string.IsNullOrEmpty(searchValue))  
  49.                     {  
  50.                         customerData = customerData.Where(m => m.CompanyName == searchValue);  
  51.                     }  
  52.   
  53.                     //total number of rows count     
  54.                     recordsTotal = customerData.Count();  
  55.                     //Paging     
  56.                     var data = customerData.Skip(skip).Take(pageSize).ToList();  
  57.                     //Returning Json Data    
  58.                     return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });  
  59.                 }  
  60.             }  
  61.             catch (Exception)  
  62.             {  
  63.                 throw;  
  64.             }  
  65.   
  66.         }  
  67.      
  68.     }  
  69. }  

Save the entire Source code and run the application.

Run Application

To access the application, enter URL - http://localhost:#####/demo/showgrid .

“#####” is localhost port number.

ASP.NET

Real-time Debugging Snapshot

In this section, you can see what values are populated when post method gets called.

ASP.NET

Search with DataTables grid

In this section we have implemented a search for only Companyname column, if you want to add another column just use or condition (“||”) with it.

ASP.NET

Adding more columns to search

ASP.NET

Snapshot while Search Data

ASP.NET

Debugging View of Search

ASP.NET

After completing with search Implementation next we are going to work on Edit Button of DataTables Grid.

Edit Event in DataTables grid

In this section first we are going add Edit Action Method in Demo Controller which will handle edit request and it will take Customer ID as input from which we are going to get details of that customer.

Code Snippet of Edit Action Method 

  1. [HttpGet]  
  2. public ActionResult Edit(int? ID)  
  3. {     
  4.     try  
  5.     {  
  6.         using (DatabaseContext _context = new DatabaseContext())  
  7.         {  
  8.             var Customer = (from customer in _context.Customers  
  9.                             where customer.CustomerID == ID  
  10.                             select customer).FirstOrDefault();  
  11.   
  12.             return View(Customer);  
  13.         }  
  14.     }  
  15.     catch (Exception)  
  16.     {  
  17.         throw;  
  18.     }     
  19. }  

After having a look on Edit action method next let’s see how to render Edit link (button).

Below is syntax for rendering Edit button

ASP.NET

Finally, you can see Edit View below.

Edit View

ASP.NET

After completing with Edit part next we are going to have a look at delete part.

Delete Event in DataTables grid

In this section first we are going add DeleteCustomer Action Method in DemoController which will handle delete request and it will take Customer ID (“ID”) as input from which we are going to delete customer data.

Code Snippet of DeleteCustomer

  1. [HttpPost]  
  2. public JsonResult DeleteCustomer(int? ID)  
  3. {  
  4.     using (DatabaseContext _context = new DatabaseContext())  
  5.     {  
  6.         var customer = _context.Customers.Find(ID);  
  7.         if (ID == null)  
  8.             return Json(data: "Not Deleted", behavior: JsonRequestBehavior.AllowGet);  
  9.         _context.Customers.Remove(customer);  
  10.         _context.SaveChanges();  
  11.   
  12.         return Json(data: "Deleted", behavior: JsonRequestBehavior.AllowGet);  
  13.     }  
  14. }  

After having a look on DeleteCustomer action method next let’s see how to render delete link (button).

Below is syntax for rendering Delete button

ASP.NET

Now you can see that we are generating simple href button and on that button, we have added an onclick event to call DeleteData function which we have not created yet, so  let’s create DeleteData function.

Code Snippet

In this part when user clicks on Delete button DeleteData function will get called and first thing it will show is confirmation alert ("Are you sure you want to delete ...?") if you click on ok (confirm) button then it will call Delete function. This function takes CustomerID as input, next we are generating URL of DeleteCustomer Action Method and passing it as ajax post request and along with it we are passing Customer ID as parameter.

If data is deleted, then we are going to get “Deleted” as a response from Deletecustomer Action Method, finally, we show alert to the user and reload grid.

  1. <script>  
  2.   
  3.     function DeleteData(CustomerID) {  
  4.         if (confirm("Are you sure you want to delete ...?")) {  
  5.             Delete(CustomerID);  
  6.         }  
  7.         else {  
  8.             return false;  
  9.         }  
  10.     }  
  11.   
  12.   
  13.     function Delete(CustomerID) {  
  14.         var url = '@Url.Content("~/")' + "Demo/DeleteCustomer";  
  15.         $.post(url, { ID: CustomerID }, function (data) {  
  16.             if (data == "Deleted") {  
  17.                 alert("Delete Customer !");  
  18.                 oTable = $('#demoGrid').DataTable();  
  19.                 oTable.draw();  
  20.             }  
  21.             else {  
  22.                 alert("Something Went Wrong!");  
  23.             }  
  24.         });  
  25.     }  
  26. </script>  

Snapshot while deleting customer

ASP.NET

Debugging View while deleting customer

ASP.NET

Finally, we have learned how to use jQuery DataTables Grid with ASP.NET CORE MVC. I hope you enjoyed the article.

Up Next
    Ebook Download
    View all
    Learn
    View all