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

jQueryUI Menu Widget using DB

Description – In this demo, we will create a menu using jQuery UI Menu Widget and all of the values will be populated through a Database table.

Step 1: Open SQL Server Management Studio and Create a Database named DemoDB and use the following script to create the table, insert sample data and also to create the Stored procedure which will be used in Visual Studio to Retrieve Data.

CREATE TABLE [dbo].[jquerymenu] (
    [ID]       INT           IDENTITY (1, 1) NOT NULL,
    [Text]     NVARCHAR (50) NULL,
    [parentId] INT           NULL,
    [isActive] BIT           NULL
);
 
SET IDENTITY_INSERT [dbo].[jquerymenu] ON
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (1, N'USA', NULL, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (2, N'India', NULL, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (3, N'UK', NULL, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (4, N'Australia', NULL, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (5, N'Virginia', 1, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (6, N'Maryland', 1, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (7, N'AP', 2, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (8, N'MP', 2, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (9, N'Karnataka', 2, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (10, N'Bangalore', 9, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (11, N'Mangalore', 9, 1)
INSERT INTO [dbo].[jquerymenu] ([ID], [Text], [parentId], [isActive]) VALUES (12, N'Mysore', 9, 0)
SET IDENTITY_INSERT [dbo].[jquerymenu] OFF
 
Create Proc spGetMenuData
as
Begin
    Select * from jquerymenu
End

Step 2: Open Visual Studio and follow the below mentioned steps.

Create project
Create a new Project
Add Class File
Add a class file
Add Webform
Add a Webform
Add Handler
Add an ASP.NET Generic Handler to Hold the request

Step 3: Add a Connection String for Connection to Database in Web.Config file.

<connectionStrings>
    <add name="DBCS" connectionString="server=.;database=DemoDB;integrated security=SSPI" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Step 4: Create Auto-populated properties in the Class file created in Step 2.

using System.Collections.Generic;
 
namespace jQueryUIMenu
{
    public class Menu
    {
        public int ID { get; set; }
        public string Text { get; set; }
        public int? parentId { get; set; }
        public bool isActive { get; set; }
        public List<Menu> List { get; set; }
    }
}

Step 5: Add the following Code to the Generic Handler which will retrieve data from Database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Configuration;
 
namespace jQueryUIMenu
{
    public class MenuHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            var list = new List<Menu>();
 
            using (var con = new SqlConnection(cs))
            {
                var cmd = new SqlCommand("spGetMenuData", con) { CommandType = CommandType.StoredProcedure };
                con.Open();
                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var menu = new Menu
                    {
                        ID = Convert.ToInt32(dr["ID"]),
                        Text = dr["Text"].ToString(),
                        parentId = dr["parentId"] != DBNull.Value ? Convert.ToInt32(dr["parentId"]) : (int?)null,
                        isActive = Convert.ToBoolean(dr["isActive"])
                    };
                    list.Add(menu);
                }
            }
            var mainList = GetMenuTree(list, null);
 
            var js = new JavaScriptSerializer();
            context.Response.Write(js.Serialize(mainList));
 
        }
 
        private List<Menu> GetMenuTree(List<Menu> list, int? parent)
        {
            return list.Where(x => x.parentId == parent).Select(x => new Menu
            {
                ID = x.ID,
                Text = x.Text,
                parentId = x.parentId,
                isActive = x.isActive,
                List = GetMenuTree(list, x.ID)
            }).ToList();
        }
 
        public bool IsReusable => false;
    }
}

Step 6: Add the following code to the Body Tag of Webform1.aspx.

<body>
    <form id="form1" runat="server">
        <div style="width150px">
            <ul id="menu"></ul>
        </div>
    </form>
</body>

Step 7: Add jQuery UI core files as shown below.

Add Nuget
Add jQuery UI Core files from Nuget Package Manager

Step 8: Add the following jQuery Code to the Head Tag of Webform1.aspx.

<head runat="server">
    <title>Dynamic Menu</title>
    <script src="Scripts/jquery-1.6.4-vsdoc.js"></script>
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery-ui-1.11.4.js"></script>
    <link href="Content/themes/base/all.css" rel="stylesheet" />
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: 'MenuHandler.ashx',
                method: 'get',
                dataType: 'json',
                success: function (data) {
                    buildMenu($('#menu'), data);
                    $('#menu').menu();
                }
            });
 
            function buildMenu(parent, items) {
                $.each(items, function () {
                    var li = $('<li>' + this.Text + '</li>');
                    if (!this.isActive) {
                        li.addClass("ui-state-disabled");
                    }
                    li.appendTo(parent);
                    if (this.List && this.List.length > 0) {
                        var ul = $('<ul></ul>');
                        ul.appendTo(li);
                        buildMenu(ul, this.List);
                    }
                });
            }
        });
    </script>
</head>

Step 9: Press Ctrl + F5 together to View the result in Browser. You will see a menu having values populated from Database.

Final

Hope you enjoyed the Example. Please share it if you think that I can be useful to others. Also comment in case of any Queries.