Display data in ASP.NET using jQuery DataTables Plugin

Description – This tutorial gives a walkthrough of jQuery Datatables plugin to display the data stored in Database using ASP.Net web Services.

Below is the screenshot of the final output that we want to achieve at the end of this tutorial.

7

So, the above is a table that allows almost all functionalities that a user wants to view data, filter data, sort data etc. This is achieved by using jQuery datatables plugin.

Step 1: First we need to create some sample data in our SQL database. Below is the script that I have used to generate test data. You can use the below script or create your own data.

Create Database Test
 
Use Test
 
Create Table Students 
(
iD int primary key not null identity(1,1),
firstName nvarchar(MAX) not null,
lastName nvarchar(MAX) not null,
feesPaid int not null,
gender nvarchar(MAX) not null,
emailId nvarchar(MAX) not null,
telephoneNumber nvarchar(MAX) not null,
dateOfBirth date not null,
isActive bit not null,
creationDate datetime not null,
lastModifiedDate datetime not null
)
GO
 
INSERT INTO Students VALUES ('Ankit','Bansal',45000, 'Male', 'ankit@a.com','2564210000','20/May/1993',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Raj','Kumar',25000, 'Male', 'raj@r.com','25400123000','20/June/1993',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Badrish','Joshi',32000, 'Male', 'badrish@b.com','10213330120','25/May/1989',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Rajesh','Negi',56000, 'Male', 'rajesh@r.com','89546332021','18/July/1978',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Rajkishor','Singh',46000, 'Male', 'rajkishor@r.com','8546795555','11/August/1985',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Neha','Arora',98652, 'Female', 'neha@n.com','96542231000','02/May/1996',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Sanjay','Sharma',65421, 'Male', 'sanjay@s.com','99876653222','25/Jan/1998',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Glenn','Block',65210, 'Male', 'glenn@g.com','54210000021','27/Feb/1990',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Sara','Silver',78900, 'Female', 'sara@s.com','89778930099','10/Sep/1989',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Lucy','Bane',23444, 'Female', 'lucy@l.com','2564210000','20/May/1993',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Suresh','Goswami',65321, 'Male', 'suresh@s.com','9876576489','21/Nov/1981',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Dinesh','Gola',76544, 'Male', 'dinesh@d.com','9899785412','15/March/1984',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Shivansh','Manaktala',87555, 'Male', 'shivansh@s.com','6755439000','17/Oct/1994',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Mahendra','Dhoni',65789, 'Male', 'mahendra@m.com','9856421003','15/March/1987',1,GETDATE(),GETDATE())
GO
 
Create Procedure getStudents
As 
Begin
   Select * from Students Where isActive=1
End

Step 2: Download jQuery Datatables plugin core files from its website. Go to http://datatables.net/download/index and follow the below steps.

Step 3: Create an Empty ASP.NET web application project and add the above downloaded files to it.

Step 4: Add a class file named students.cs with some auto-implemented properties. You can copy and paste the below code if you are using my SQL script.

using System;
 
namespace dataTablesPlugin
{
    class Students
    {
        public int iD { getset; }
        public string firstName { getset; }
        public string lastName { getset; }
        public int feesPaid { getset; }
        public string gender { getset; }
        public string emailId { getset; }
        public string telephoneNumber { getset; }
        public DateTime dateOfBirth { getset; }
    }
}

Explanation: We have created properties in the class file with the same name as that of our database table columns. This helps us to retrieve data from sql database.

Step 5: Create a connection string in the Web.config file.

<connectionStrings>
    <add connectionString="Data Source=.;Initial Catalog=Test;Integrated Security=True" name="dbcs" providerName="System.Data.SqlClient"/>
  </connectionStrings>

The above string is used to connect to Database using .net sql client.

Step 6: Add a ASP.NET web service named StudentService.asmx and add the following code to it.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
 
namespace dataTablesPlugin
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class StudentService : System.Web.Services.WebService
    {
        [WebMethod]
        public void GetStudents()
        {
            var cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            var students = new List<Students>();
            using (var con = new SqlConnection(cs))
            {
                var cmd = new SqlCommand("getStudents", con) {CommandType = CommandType.StoredProcedure};
                con.Open();
                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var student = new Students
                    {
                        iD = Convert.ToInt32(dr[0].ToString()),
                        firstName = dr[1].ToString(),
                        lastName = dr[2].ToString(),
                        feesPaid = Convert.ToInt32(dr[3].ToString()),
                        gender = dr[4].ToString(),
                        emailId = dr[5].ToString(),
                        telephoneNumber = dr[6].ToString(),
                        dateOfBirth = Convert.ToDateTime(dr[7].ToString())
                    };
                    students.Add(student);
                }
            }
            var js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(students));
        }
    }
}

The above code is a simple ADO.NET code that create a list of Students and retrieve data from database stored procedure and read each property value from it and stores it in our class properties. At the last of this code, JavaScriptSerializer class is used to convert the received data in JSON format so that our Datatables plugin can consume that data using AJAX call.

Now Lets quickly test our web service if it is returning the correct data or not. Press ctrl + F5.

WebServiceCheck

Step 7: Add a webform to the project.

Step 8: Add the following references in the head section of the HTML.

    <script src="DataTables/jQuery-2.2.0/jquery-2.2.0.js"></script>
    <script src="DataTables/DataTables-1.10.11/js/jquery.dataTables.js"></script>
    <link href="DataTables/DataTables-1.10.11/css/jquery.dataTables.css" rel="stylesheet" />
    <link href="DataTables/Bootstrap-3.3.6/css/bootstrap.css" rel="stylesheet" />

The above references are of core jQuery, datatables plugin jquery, datatables plugin css and bootstrap css.

Step 9: Add the following HTML code to the Body tag.

<body>
    <form id="form1" runat="server">
        <div style="padding10pxborder5px solid blackmargin-top50px" class="container-fluid">
            <div>
                <b class="label label-danger" style="padding8.5px">Click to Show or Hide Column:</b>
                <div class="btn-group btn-group-sm">
                    <a class="showHide btn btn-primary" data-columnindex="0">ID</a>
                    <a class="showHide btn btn-primary" data-columnindex="1">FirstName</a>
                    <a class="showHide btn btn-primary" data-columnindex="2">LastName</a>
                    <a class="showHide btn btn-primary" data-columnindex="3">FeesPaid</a>
                    <a class="showHide btn btn-primary" data-columnindex="4">Gender</a>
                    <a class="showHide btn btn-primary" data-columnindex="5">Email</a>
                    <a class="showHide btn btn-primary" data-columnindex="6">TelephoneNumber</a>
                    <a class="showHide btn btn-primary" data-columnindex="7">Date of Birth</a>
                </div>
            </div>
            <br />
            <table id="studentTable" class="table table-responsive table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Fees Paid</th>
                        <th>Gender</th>
                        <th>Email</th>
                        <th>Telephone Number</th>
                        <th>Date of Birth</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>ID</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Fees Paid</th>
                        <th>Gender</th>
                        <th>Email</th>
                        <th>Telephone Number</th>
                        <th>Date of Birth</th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </form>
</body>

We have just declared a table with header and footer. The main content will be displayed using jQuery AJAX call using our web service.

Step 10: Add the custom CSS to the Head section.

    <style>
        .showHide {
            cursorpointer;
        }
    </style>

Step 11: Add the following jQuery Code to the Head section.

    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "studentService.asmx/GetStudents",
                success: function (data) {
                    var datatableVariable = $('#studentTable').DataTable({
                        data: data,
                        columns: [
                            { 'data''iD' },
                            { 'data''firstName' },
                            { 'data''lastName' },
                            {
                                'data''feesPaid''render'function (feesPaid) {
                                    return '$ ' + feesPaid;
                                }
                            },
                            { 'data''gender' },
                            { 'data''emailId' },
                            { 'data''telephoneNumber' },
                            {
                                'data''dateOfBirth''render'function (date) {
                                    var date = new Date(parseInt(date.substr(6)));
                                    var month = date.getMonth() + 1;
                                    return date.getDate() + "/" + month + "/" + date.getFullYear();
                                }
                            }]
                    });
                    $('#studentTable tfoot th').each(function () {
                        var placeHolderTitle = $('#studentTable thead th').eq($(this).index()).text();
                        $(this).html('<input type="text" class="form-control input input-sm" placeholder = "Search ' + placeHolderTitle + '" />');
                    });
                    datatableVariable.columns().every(function () {
                        var column = this;
                        $(this.footer()).find('input').on('keyup change'function () {
                            column.search(this.value).draw();
                        });
                    });
                    $('.showHide').on('click'function () {
                        var tableColumn = datatableVariable.column($(this).attr('data-columnindex'));
                        tableColumn.visible(!tableColumn.visible());
                    });
                }
            });
 
        });
    </script>

Explanation:

1. We use the jquery ajax function to call our web service by mentioning its URL in the URL option.

2. If the call to the service is success, then we call DataTable function of the datatables plugin API which converts our table into a multi-purpose table which can help to show data, filter data, sort data, paging of data, hiding / showing columns etc.

3. We specify the columns that we want to display after getting data from the AJAX call.

4. To allow searching on each column, we use the each function of jQuery and append an input element which displays a textbox at the bottom of each column.

5. To show/hide columns, we are using visible function of jQuery and data-columnindex attribute.

Step 12: Press Ctrl + F5 together and you will see the following output and this is what we want to achieve.

Please comment if I missed anything or give your reviews. If you like my tutorial, please visit my blog and read my other articles too and share. Thanks.

Advertisements

One thought on “Display data in ASP.NET using jQuery DataTables Plugin

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s