Below is the screenshot of the final output that we want to achieve at the end of this tutorial.
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 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 following 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', '[email protected]','2564210000','20/May/1993',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Raj','Kumar',25000, 'Male', '[email protected]','25400123000','20/June/1993',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Badrish','Joshi',32000, 'Male', '[email protected]','10213330120','25/May/1989',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Rajesh','Negi',56000, 'Male', '[email protected]','89546332021','18/July/1978',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Rajkishor','Singh',46000, 'Male', '[email protected]','8546795555','11/August/1985',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Neha','Arora',98652, 'Female', '[email protected]','96542231000','02/May/1996',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Sanjay','Sharma',65421, 'Male', '[email protected]','99876653222','25/Jan/1998',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Glenn','Block',65210, 'Male', '[email protected]','54210000021','27/Feb/1990',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Sara','Silver',78900, 'Female', '[email protected]','89778930099','10/Sep/1989',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Lucy','Bane',23444, 'Female', '[email protected]','2564210000','20/May/1993',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Suresh','Goswami',65321, 'Male', '[email protected]','9876576489','21/Nov/1981',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Dinesh','Gola',76544, 'Male', '[email protected]','9899785412','15/March/1984',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Shivansh','Manaktala',87555, 'Male', '[email protected]','6755439000','17/Oct/1994',1,GETDATE(),GETDATE())
- GO
- INSERT INTO Students VALUES ('Mahendra','Dhoni',65789, 'Male', '[email protected]','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 following code if you are using SQL script.
- using System;
-
- namespace dataTablesPlugin
- {
- class Students
- {
- public int iD { get; set; }
- public string firstName { get; set; }
- public string lastName { get; set; }
- public int feesPaid { get; set; }
- public string gender { get; set; }
- public string emailId { get; set; }
- public string telephoneNumber { get; set; }
- public DateTime dateOfBirth { get; set; }
- }
- }
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 retrieves data from database stored procedure and reads 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 let us quickly test our web service if it is returning the correct data or not. Press CTRL + F5.
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="padding: 10px; border: 5px solid black; margin-top: 50px" class="container-fluid">
- <div>
- <b class="label label-danger" style="padding: 8.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 {
- cursor: pointer;
- }
- </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
- We use the jquery ajax function to call our web service by mentioning its URL in the URL option.
- If the call to the service is successful, 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.
- We specify the columns that we want to display after getting data from the AJAX call.
- 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.
- 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.