ASP.NET Webform - Datatables JQuery plugin Server Side Integration

Datatables is a quite popular JQuery based plugin. There are a lot of flavors of Datatables plugins and it supports many major web programming technologies.

In this article, I shall be focusing more on how Datatables plugin can be integrated with classic ASP.NET webform server side. If anyone is interested to integrate this beautiful plugin with ASP.NET MVC5 server then here is the link.

output

Following are some prerequisites before you proceed any further in this tutorial,

Prerequisites:

The prerequisites include knowledge about the following technologies: 
  1. Classic ASP.NET webform.
  2. HTML.
  3. Javascript.
  4. AJAX.
  5. CSS.
  6. Bootstrap.
  7. C# programming.
  8. C# LINQ.
  9. JQuery.
  10.  WebMethod attribute

The example code is developed in Microsoft Visual Studio 2015 Enterprise. I am using SalesOrderDetail table extract from Adventure Works Sample Database.

Let's begin now.

  1. Create new Webform web application project and name it "JqDatatablesWebfoms".
  2. Since the project is created with ".Net 4.5.2" framework therefore you will see its project hierarchy a bit similar to MVC5 hierarchy. If that's the case then you will see "RouteConfig.cs" file, open it and replace it with following code,
    1. ...  
    2.     public static void RegisterRoutes(RouteCollection routes)    
    3.      {    
    4.        ...    
    5.        settings.AutoRedirectMode = RedirectMode.Off; // RedirectMode.Permanent    
    6.        ...   
    7.      }  
    8. ... 
    In above code, I have changed "RedirectMode.Permanent" to "RedirectMode.Off". The reason is that since, I am going to use ajax call in datatables plugin, so, if redirect mode in friendly URL is not off then my ajax call will redirect to root page and ajax call to serverside will not work.

  3. Now, create your website require layout template and incorporate links of the require scripts and styles into "Site.Master" file.
  4. Create "Default.aspx" page file and create HTML table as shown below,
    1. ..  
    2. <table class="table table-striped table-bordered table-hover"    
    3.        id="TableId"    
    4.        cellspacing="0"    
    5.        align="center"    
    6.        width="100%">    
    7.    <thead>    
    8.       <tr>    
    9.          <th>Sr</th>    
    10.          <th>Order Track Number</th>    
    11.          <th>Quantity</th>    
    12.          <th>Product Name</th>    
    13.          <th>Special Offer</th>    
    14.          <th>Unit Price</th>    
    15.          <th>Unit Price Discount</th>    
    16.       </tr>    
    17.    </thead>    
    18. </table>          
    19. ... 
    Here, I have created a table holder that will be integrated with Datatables plugin with data from server side. I have only provided table header information here, since the data will be integrated from server side.

  5. Now create two new models under "Model", name it "SalesOrderDetail.cs" & "DataTables.cs" and add following properties in them,
    1. ...  
    2.    public class SalesOrderDetail    
    3.    {    
    4.      public int Sr { getset; }    
    5.      public string OrderTrackNumber { getset; }    
    6.      public int Quantity { getset; }    
    7.      public string ProductName { getset; }    
    8.      public string SpecialOffer { getset; }    
    9.      public double UnitPrice { getset; }    
    10.      public double UnitPriceDiscount { getset; }    
    11.    }   
    12. ...  
    13.   
    14. ...  
    15.    public class DataTables    
    16.    {    
    17.      public int draw { getset; }    
    18.      public int recordsTotal { getset; }    
    19.      public int recordsFiltered { getset; }    
    20.      public List<SalesOrderDetail> data { getset; }    
    21.    }  
    22. ... 
  6. Load the provided sample data from the text file into list object.

  7. Now, create new script file under "Scripts" folder, name it "custom-datatable.js" and place following code in it,
    1. ...  
    2.    $('#TableId').DataTable(    
    3.    {    
    4.      ...  
    5.      "serverSide"true,    
    6.      "ajax":    
    7.        {    
    8.          "url""Default.aspx/GetData",    
    9.          "contentType""application/json",    
    10.          "type""GET",    
    11.          "dataType""JSON",    
    12.          "data"function (d)    
    13.          {    
    14.            return d;    
    15.          },    
    16.          "dataSrc"function (json)    
    17.          {    
    18.            json.draw = json.d.draw;    
    19.            json.recordsTotal = json.d.recordsTotal;    
    20.            json.recordsFiltered = json.d.recordsFiltered;    
    21.            json.data = json.d.data;    
    22.            var return_data = json;    
    23.            return return_data.data;    
    24.          }    
    25.        },    
    26.      "columns": [    
    27.            { "data""Sr" },    
    28.            { "data""OrderTrackNumber" },    
    29.            { "data""Quantity" },    
    30.            { "data""ProductName" },    
    31.            { "data""SpecialOffer" },    
    32.            { "data""UnitPrice" },    
    33.            { "data""UnitPriceDiscount" }    
    34.      ]    
    35.      ...  
    36.    });   
    37. ... 
    The above code will display the server side data into the table that we have created earlier into our "Default.aspx" page using Jquery Datatables..

  8. Now, in "Default.aspx.cs" file let's create "GetData" method as follow,
    1. ...  
    2.      [WebMethod]    
    3.      [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]    
    4.      public static object GetData()    
    5.      {    
    6.        // Initialization.    
    7.        DataTables result = new DataTables();   
    8.   
    9.        ...   
    10.    
    11.        // Capture Jquery Datatables Plugin Properties.    
    12.        string search = HttpContext.Current.Request.Params["search[value]"];    
    13.        string draw = HttpContext.Current.Request.Params["draw"];    
    14.        string order = HttpContext.Current.Request.Params["order[0][column]"];    
    15.        string orderDir = HttpContext.Current.Request.Params["order[0][dir]"];    
    16.        int startRec = Convert.ToInt32(HttpContext.Current.Request.Params["start"]);    
    17.        int pageSize = Convert.ToInt32(HttpContext.Current.Request.Params["length"]);   
    18.    
    19.        // Load data from text file.   
    20.        List<SalesOrderDetail> data = new List<SalesOrderDetail>();  
    21.   
    22.       ...   
    23.   
    24.         // Configure Jquery Datatable property Total record count property.    
    25.        int totalRecords = data.Count;  
    26.     
    27.        // Apply server-side data searching.   
    28.    
    29.        ...  
    30.   
    31.        // Apply server-side Sorting.    
    32.   
    33.        ...  
    34.   
    35.        // Configure Jquery Datatable property Filter record count property after applying searching and sorting.    
    36.        int recFilter = data.Count;   
    37.    
    38.        // Apply server-side pagination.    
    39.   
    40.        ...  
    41.   
    42.        // Mapping final configuration settings for Jquery Datatables plugin.    
    43.        result.draw = Convert.ToInt32(draw);    
    44.        result.recordsTotal = totalRecords;    
    45.        result.recordsFiltered = recFilter;    
    46.        result.data = data;     
    47.   
    48.       ...  
    49.   
    50.        // Return info.    
    51.        return result;    
    52.      }  
    53. ... 

In above piece of code, we have created a WebMethod which is based on searching, sorting and pagination information sent from Datatebles plugin, following have been done i.e.

  1. Data is being loaded first.
  2. Data is being churned out base on searching criteria.
  3. Data is sorted by provided column in provided order.
  4. Data is then paginated.
  5. Data is returned.

"GetData" function will be executed each time the table is being searched, sorted or new page is accessed. Here are the  following two lines which are important,

  1. // Total record count.   
  2. int totalRecords = data.Count;   
  3.   
  4. // Filter record count.   
  5. int recFilter = data.Count;  
First line determines the actual amount of records that exist in the list and second line determines the amount of records that are left after applying filtering.
 
Now, execute the project and you will be able to see following,
 
output
 
output

Conclusion

This article was about Datatables plugin server side integration with ASP.NET Webform. In this article you will learn to integrate server side data, searching, sorting and pagination information with Datatebles plugin using ASP.NET classic webforms. I have also created a post for integrating Datatables JQuery base plugin server side integration with ASP.NET MVC5.


Similar Articles