In this article we will learn how to work with jQuery Datatables with server side data. Here we are going to use a MVC application with jQuery and other required packages installed in it. If you are new to MVC, you can always get the tips/tricks/blogs about that here under MVC Tips. jQuery Datatable is a client side grid control which is lightweight and easy to use. But when it comes to a grid control, it must be usable when it supports the server side loading of data. This control is perfect for that. I guess it is enough for the introduction. Now we will start using our grid. I hope you will like this.

You can always download the source code here:

Create a MVC application

Click File, New, then Project and then select MVC application. Before going to start the coding part, make sure that all the required extensions/ references are installed. Below are the required things to start with.

You can add all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.

Manage NuGet Package Window
Figure: Manage NuGet Package Window

Once you have installed those items, please make sure that all the items (jQuery, Datatables JS files) are loaded in your scripts folder.

Using the code

Now let us add the needed references.

Include the references in your _Layout.cshtml

As we have already installed all the packages we need, now we need to add the references, right? After adding the reference, your _Layout.cshtml will look like below.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>@ViewBag.Title - My ASP.NET Application</title>
  7. <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
  8. <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
  9. <link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
  10. <script src="~/Scripts/modernizr-2.6.2.js"></script>
  11. <script src="~/scripts/jquery-2.2.0.min.js"></script>
  12. <script src="~/scripts/jquery-ui-1.10.2.min.js"></script>
  13. <script src="~/scripts/DataTables/jquery.dataTables.min.js"></script>
  14. <script src="~/scripts/MyScripts.js"></script>
  15. <script src="~/Scripts/bootstrap.min.js"></script>
  16. </head>
  17. <body>
  18. <div class="navbar navbar-inverse navbar-fixed-top">
  19. <div class="container">
  20. <div class="navbar-header">
  21. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  22. <span class="icon-bar"></span>
  23. <span class="icon-bar"></span>
  24. <span class="icon-bar"></span>
  25. </button> @Html.ActionLink("jQuery Datatable With Server Side Data", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
  26. </div>
  27. <div class="navbar-collapse collapse">
  28. <ul class="nav navbar-nav">
  29. </ul>
  30. </div>
  31. </div>
  32. </div>
  33. <div class="container body-content">
  34. @RenderBody()
  35. <hr />
  36. <footer>
  37. <p>© @DateTime.Now.Year - <a href="http://sibeeshpassion.com">Sibeesh Passion</a></p>
  38. </footer>
  39. </div>
  40. </body>
  41. </html>
Here MyScripts.js is the JavaScript file where we are going to write our own scripts.

Add a normal MVC controller

Now we will add a normal MVC controller in our app. Once you add that you can see an ActionResult is created for us.
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }
Right click on the controller, and click add view, that will create a View for you. Now we will change the view as follows.
  1. @{
  2. ViewBag.Title = "jQuery Datatable With Server Side Data";
  3. }
  4. <h2>jQuery Datatable With Server Side Data</h2>
  5. <table id="myGrid" class="table">
  6. <thead>
  7. <tr>
  8. <th>SalesOrderID</th>
  9. <th>SalesOrderDetailID</th>
  10. <th>CarrierTrackingNumber</th>
  11. <th>OrderQty</th>
  12. <th>ProductID</th>
  13. <th>UnitPrice</th>
  14. </tr>
  15. </thead>
  16. <tfoot>
  17. <tr>
  18. <th>SalesOrderID</th>
  19. <th>SalesOrderDetailID</th>
  20. <th>CarrierTrackingNumber</th>
  21. <th>OrderQty</th>
  22. <th>ProductID</th>
  23. <th>UnitPrice</th>
  24. </tr>
  25. </tfoot>
  26. </table>
So we have set the headers and footer for our grid, where we are going to load the grid control in the table myGrid.

So far the UI part is done, now it is time to set up our database and entity model. Are you ready?

Create a database

The following query can be used to create a database in your SQL Server.
  1. USE [master]
  2. GO
  3. /****** Object: Database [TrialsDB] Script Date: 17-Feb-16 10:21:17 PM ******/
  4. CREATE DATABASE [TrialsDB]
  5. CONTAINMENT = NONE
  6. ON PRIMARY
  7. ( NAME = N'TrialsDB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
  8. LOG ON
  9. ( NAME = N'TrialsDB_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
  10. GO
  11. ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110
  12. GO
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
  14. begin
  15. EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'
  16. end
  17. GO
  18. ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF
  19. GO
  20. ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF
  21. GO
  22. ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF
  23. GO
  24. ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF
  25. GO
  26. ALTER DATABASE [TrialsDB] SET ARITHABORT OFF
  27. GO
  28. ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF
  29. GO
  30. ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON
  31. GO
  32. ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF
  33. GO
  34. ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON
  35. GO
  36. ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF
  37. GO
  38. ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL
  39. GO
  40. ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF
  41. GO
  42. ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF
  43. GO
  44. ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF
  45. GO
  46. ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF
  47. GO
  48. ALTER DATABASE [TrialsDB] SET DISABLE_BROKER
  49. GO
  50. ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
  51. GO
  52. ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF
  53. GO
  54. ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF
  55. GO
  56. ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
  57. GO
  58. ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE
  59. GO
  60. ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF
  61. GO
  62. ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF
  63. GO
  64. ALTER DATABASE [TrialsDB] SET RECOVERY FULL
  65. GO
  66. ALTER DATABASE [TrialsDB] SET MULTI_USER
  67. GO
  68. ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM
  69. GO
  70. ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF
  71. GO
  72. ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
  73. GO
  74. ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS
  75. GO
  76. ALTER DATABASE [TrialsDB] SET READ_WRITE
  77. GO
Now we will create a table.

Create table in database

Below is the query to create table in database.
  1. USE [TrialsDB]
  2. GO
  3. /****** Object: Table [dbo].[SalesOrderDetail] Script Date: 19-Feb-16 12:30:55 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. CREATE TABLE [dbo].[SalesOrderDetail](
  9. [SalesOrderID] [int] NOT NULL,
  10. [SalesOrderDetailID] [int] IDENTITY(1,1) NOT NULL,
  11. [CarrierTrackingNumber] [nvarchar](25) NULL,
  12. [OrderQty] [smallint] NOT NULL,
  13. [ProductID] [int] NOT NULL,
  14. [SpecialOfferID] [int] NOT NULL,
  15. [UnitPrice] [money] NOT NULL,
  16. [UnitPriceDiscount] [money] NOT NULL,
  17. [LineTotal] AS (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0))),
  18. [rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
  19. [ModifiedDate] [datetime] NOT NULL,
  20. CONSTRAINT [PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID] PRIMARY KEY CLUSTERED
  21. (
  22. [SalesOrderID] ASC,
  23. [SalesOrderDetailID] ASC
  24. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  25. ) ON [PRIMARY]
  26. GO
Insert data to table

To insert the data, I will attach a database script file along with the download file, you can either run that or insert some data using the below query. By the way if you would like to know how to generate scripts with data in SQL Server, you can check here.
  1. USE [TrialsDB]
  2. GO
  3. INSERT INTO [dbo].[SalesOrderDetail]
  4. ([SalesOrderID]
  5. ,[CarrierTrackingNumber]
  6. ,[OrderQty]
  7. ,[ProductID]
  8. ,[SpecialOfferID]
  9. ,[UnitPrice]
  10. ,[UnitPriceDiscount]
  11. ,[rowguid]
  12. ,[ModifiedDate])
  13. VALUES
  14. (<SalesOrderID, int,>
  15. ,<CarrierTrackingNumber, nvarchar(25),>
  16. ,<OrderQty, smallint,>
  17. ,<ProductID, int,>
  18. ,<SpecialOfferID, int,>
  19. ,<UnitPrice, money,>
  20. ,<UnitPriceDiscount, money,>
  21. ,<rowguid, uniqueidentifier,>
  22. ,<ModifiedDate, datetime,>)
  23. GO
Along with this, we can create a new stored procedure which will fetch the data. The following is the query to create the stored procedure.
  1. USE [TrialsDB]
  2. GO
  3. /****** Object: StoredProcedure [dbo].[usp_Get_SalesOrderDetail] Script Date: 19-Feb-16 12:33:43 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. -- =============================================
  9. -- Author: <Author,Sibeesh Venu>
  10. -- Create date: <Create Date, 18-Feb-2016>
  11. -- Description: <Description,To fetch SalesOrderDetail>
  12. -- =============================================
  13. ALTER PROCEDURE [dbo].[usp_Get_SalesOrderDetail]
  14. AS
  15. BEGIN
  16. -- SET NOCOUNT ON added to prevent extra result sets from
  17. -- interfering with SELECT statements.
  18. SET NOCOUNT ON;
  19. -- Select statements for procedure here
  20. SELECT top(100) SalesOrderID,SalesOrderDetailID,CarrierTrackingNumber,OrderQty,ProductID,UnitPrice,ModifiedDate from dbo.SalesOrderDetail
  21. END
Next thing we are going to do is creating an ADO.NET Entity Data Model.

Create Entity Data Model

Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the processes, you can see the edmx file and other files in your model folder.

Now we will go back to our controller and add a new JsonResult which can be called via a new jQuery Ajax request. No worries, we will create that Ajax request later. Once you add the Jsonresult action, I hope your controller will look like this.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using jQuery_Datatable_With_Server_Side_Data.Models;
  7. namespace jQuery_Datatable_With_Server_Side_Data.Controllers
  8. {
  9. public class HomeController: Controller
  10. {
  11. TrialsDBEntities tdb;
  12. Sales sa = new Sales();
  13. public ActionResult Index()
  14. {
  15. return View();
  16. }
  17. public JsonResult GetGata()
  18. {
  19. try
  20. {
  21. using(tdb = new TrialsDBEntities())
  22. {
  23. var myList = sa.GetSales(tdb);
  24. return Json(myList, JsonRequestBehavior.AllowGet);
  25. }
  26. }
  27. catch (Exception)
  28. {
  29. throw;
  30. }
  31. }
  32. }
  33. }
Here TrialsDBEntities is our entity class. Please note that to use the model classes in your controller, you must add the reference as follows.
  1. using jQuery_Datatable_With_Server_Side_Data.Models;
I know all of you are familiar with this, I am just saying! Now can we create a function GetSales in our model class Sales ?.
  1. public object GetSales(TrialsDBEntities tdb)
  2. {
  3. try
  4. {
  5. var myList = ((from l in tdb.SalesOrderDetails select new
  6. {
  7. SalesOrderID = l.SalesOrderID,
  8. SalesOrderDetailID = l.SalesOrderDetailID,
  9. CarrierTrackingNumber = l.CarrierTrackingNumber,
  10. OrderQty = l.OrderQty,
  11. ProductID = l.ProductID,
  12. UnitPrice = l.UnitPrice
  13. }).OrderBy(l => l.SalesOrderID)).Take(100).ToList();
  14. return myList;
  15. }
  16. catch (Exception)
  17. {
  18. throw new NotImplementedException();
  19. }
  20. }
We use normal LINQ queries here, and we take only 100 records to load for now. If you don’t want to use this method you can call our stored procedure which we have created while creating our database. You can call this as explained in the below function.
  1. public List < SalesOrderDetail > GetSalesSP(TrialsDBEntities tdb)
  2. {
  3. try
  4. {
  5. var myList = tdb.Database.SqlQuery < SalesOrderDetail > ("EXEC usp_Get_SalesOrderDetail").ToList();
  6. return myList;
  7. }
  8. catch (Exception)
  9. {
  10. throw new NotImplementedException();
  11. }
  12. }
Now the only thing pending is to call our controller JsonResult action, right? We will do some code in our MyScript.js file.
  1. $(document).ready(function() {
  2. $('#myGrid').DataTable({
  3. "ajax": {
  4. "url": "../Home/GetGata/",
  5. "dataSrc": ""
  6. },
  7. "columns": [{
  8. "data": "SalesOrderID"
  9. }, {
  10. "data": "SalesOrderDetailID"
  11. }, {
  12. "data": "CarrierTrackingNumber"
  13. }, {
  14. "data": "OrderQty"
  15. }, {
  16. "data": "ProductID"
  17. }, {
  18. "data": "UnitPrice"
  19. }]
  20. });
  21. });
Here “dataSrc”: “” should be used if you have a plain JSON data. The sample data can be seen below.
  1. [{"SalesOrderID":43659,"SalesOrderDetailID":2,"CarrierTrackingNumber":"4911-403C-98","OrderQty":1,"ProductID":776,"UnitPrice":2024.994},{"SalesOrderID":43659,"SalesOrderDetailID":3,"CarrierTrackingNumber":"4911-403C-98","OrderQty":3,"ProductID":777,"UnitPrice":2024.994},{"SalesOrderID":43659,"SalesOrderDetailID":4,"CarrierTrackingNumber":"4911-403C-98","OrderQty":1,"ProductID":778,"UnitPrice":2024.994},{"SalesOrderID":43659,"SalesOrderDetailID":5,"CarrierTrackingNumber":"4911-403C-98","OrderQty":1,"ProductID":771,"UnitPrice":2039.994},{"SalesOrderID":43659,"SalesOrderDetailID":6,"CarrierTrackingNumber":"4911-403C-98","OrderQty":1,"ProductID":772,"UnitPrice":2039.994},{"SalesOrderID":43659,"SalesOrderDetailID":7,"CarrierTrackingNumber":"4911-403C-98","OrderQty":2,"ProductID":773,"UnitPrice":2039.994},{"SalesOrderID":43659,"SalesOrderDetailID":8,"CarrierTrackingNumber":"4911-403C-98","OrderQty":1,"ProductID":774,"UnitPrice":2039.994},{"SalesOrderID":43659,"SalesOrderDetailID":9,"CarrierTrackingNumber":"4911-403C-98","OrderQty":3,"ProductID":714,"UnitPrice":28.8404},{"SalesOrderID":43659,"SalesOrderDetailID":10,"CarrierTrackingNumber":"4911-403C-98","OrderQty":1,"ProductID":716,"UnitPrice":28.8404}]
We have done everything!. Can we see the output now?

Output

jQuery Datatable With Server Side Data
Figure: jQuery Datatable With Server Side Data

jQuery Datatable With Server Side Data Search
Figure: jQuery Datatable With Server Side Data Search
Please see this article in my blog here
Conclusion

Did I miss anything that you may think is needed? Did you use jQuery Datatables in your application? Have you ever wanted to do this requirement? Did you find this post useful? I hope you liked this article. Please sharewith me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.
Read more articles on ASP.NET: