Integrating Datatables JQuery Plugin in ASP.NET Webforms

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 the Datatables plugin can be integrated with the classic ASP.NET web form server side. If anyone is interested in integrating this beautiful plugin with the ASP.NET MVC5 server then here is the link.

Datatables plugin

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 the SalesOrderDetail table extract from the Adventure Works Sample Database.

Let's begin now.

  1. Create a new Webform web application project and name it "JqDatatablesWebfoms".
  2. Since the project is created with the ".Net 4.5.2" framework, therefore, you will see its project hierarchy is a bit similar to the MVC5 hierarchy. If that's the case then you will see the "RouteConfig.cs" file, open it and replace it with the following code,
    ...
    public static void RegisterRoutes(RouteCollection routes)
    {
        ...
        settings.AutoRedirectMode = RedirectMode.Off; // RedirectMode.Permanent
        ...
    }
    ...
    
    In the above code, I have changed "RedirectMode.Permanent" to "RedirectMode.Off". The reason is that I am going to use Ajax call in the data tables plugin, so, if the redirect mode in the friendly URL is not off then my Ajax call will redirect to the root page and Ajax call to serverside will not work.
  3. Now, create your website's required layout template and incorporate links of the required scripts and styles into the "Site. Master" file.
  4. Create a "Default.aspx" page file and create an HTML table as shown below,
    <table class="table table-striped table-bordered table-hover" id="TableId" cellspacing="0" align="center" width="100%">
        <thead>
            <tr>
                <th>Sr</th>
                <th>Order Track Number</th>
                <th>Quantity</th>
                <th>Product Name</th>
                <th>Special Offer</th>
                <th>Unit Price</th>
                <th>Unit Price Discount</th>
            </tr>
        </thead>
    </table>
    
    Here, I have created a table holder that will be integrated with the Datatables plugin with data from the server side. I have only provided table header information here since the data will be integrated from the server side.
  5. Now create two new models under "Model", and name them "SalesOrderDetail.cs" & "DataTables.cs" and add the following properties to them,
    public class SalesOrderDetail
    {
        public int Sr { get; set; }
        public string OrderTrackNumber { get; set; }
        public int Quantity { get; set; }
        public string ProductName { get; set; }
        public string SpecialOffer { get; set; }
        public double UnitPrice { get; set; }
        public double UnitPriceDiscount { get; set; }
    }
    
    public class DataTables
    {
        public int draw { get; set; }
        public int recordsTotal { get; set; }
        public int recordsFiltered { get; set; }
        public List<SalesOrderDetail> data { get; set; }
    }
    
  6. Load the provided sample data from the text file into the list object.
  7. Now, create a new script file under the "Scripts" folder, name it "custom-datatable.js" and place the following code in it,
    $('#TableId').DataTable({
        ...
        "serverSide": true,
        "ajax": {
            "url": "Default.aspx/GetData",
            "contentType": "application/json",
            "type": "GET",
            "dataType": "JSON",
            "data": function (d) {
                return d;
            },
            "dataSrc": function (json) {
                json.draw = json.d.draw;
                json.recordsTotal = json.d.recordsTotal;
                json.recordsFiltered = json.d.recordsFiltered;
                json.data = json.d.data;
                var return_data = json;
                return return_data.data;
            }
        },
        "columns": [
            { "data": "Sr" },
            { "data": "OrderTrackNumber" },
            { "data": "Quantity" },
            { "data": "ProductName" },
            { "data": "SpecialOffer" },
            { "data": "UnitPrice" },
            { "data": "UnitPriceDiscount" }
        ]
        ...
    });
    
    The above code will display the server-side data in the table that we created earlier into our "Default.aspx" page using Jquery Datatables.
  8. Now, in the "Default.aspx.cs" file let's create the "GetData" method as follows,
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
    public static object GetData()
    {
        // Initialization.
        DataTables result = new DataTables();
    
        // Capture Jquery Datatables Plugin Properties.
        string search = HttpContext.Current.Request.Params["search[value]"];
        string draw = HttpContext.Current.Request.Params["draw"];
        string order = HttpContext.Current.Request.Params["order[0][column]"];
        string orderDir = HttpContext.Current.Request.Params["order[0][dir]"];
        int startRec = Convert.ToInt32(HttpContext.Current.Request.Params["start"]);
        int pageSize = Convert.ToInt32(HttpContext.Current.Request.Params["length"]);
    
        // Load data from text file.
        List<SalesOrderDetail> data = new List<SalesOrderDetail>();
    
        // Configure Jquery Datatable property Total record count property.
        int totalRecords = data.Count;
    
        // Apply server-side data searching.
    
        // Apply server-side Sorting.
    
        // Configure Jquery Datatable property Filter record count property after applying searching and sorting.
        int recFilter = data.Count;
    
        // Apply server-side pagination.
    
        // Mapping final configuration settings for Jquery Datatables plugin.
        result.draw = Convert.ToInt32(draw);
        result.recordsTotal = totalRecords;
        result.recordsFiltered = recFilter;
        result.data = data;
    
        // Return info.
        return result;
    }
    

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

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

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

// Total record count.
int totalRecords = data.Count;

// Filter record count.
int recFilter = data.Count;

The first line determines the actual amount of records that exist in the list and the second line determines the amount of records that are left after applying filtering.

Now, execute the project and you will be able to see the following,

Project

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 the Datatebles plugin using ASP.NET classic web forms. I have also created a post for integrating Datatables JQuery base plugin server-side integration with ASP.NET MVC5.


Similar Articles