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.
- Datatables Package
- jQuery
You can add all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.
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.
- <!DOCTYPE html>
- <html>
-
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - My ASP.NET Application</title>
- <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
- <link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
- <script src="~/Scripts/modernizr-2.6.2.js"></script>
- <script src="~/scripts/jquery-2.2.0.min.js"></script>
- <script src="~/scripts/jquery-ui-1.10.2.min.js"></script>
- <script src="~/scripts/DataTables/jquery.dataTables.min.js"></script>
- <script src="~/scripts/MyScripts.js"></script>
- <script src="~/Scripts/bootstrap.min.js"></script>
- </head>
-
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button> @Html.ActionLink("jQuery Datatable With Server Side Data", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
- </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- </ul>
- </div>
- </div>
- </div>
-
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <p>© @DateTime.Now.Year - <a href="http://sibeeshpassion.com">Sibeesh Passion</a></p>
- </footer>
- </div>
- </body>
-
- </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.
- public ActionResult Index()
- {
- return View();
- }
Right click on the controller, and click add view, that will create a View for you. Now we will change the view as follows.
- @{
- ViewBag.Title = "jQuery Datatable With Server Side Data";
- }
-
- <h2>jQuery Datatable With Server Side Data</h2>
-
- <table id="myGrid" class="table">
- <thead>
- <tr>
- <th>SalesOrderID</th>
- <th>SalesOrderDetailID</th>
- <th>CarrierTrackingNumber</th>
- <th>OrderQty</th>
- <th>ProductID</th>
- <th>UnitPrice</th>
- </tr>
- </thead>
- <tfoot>
- <tr>
- <th>SalesOrderID</th>
- <th>SalesOrderDetailID</th>
- <th>CarrierTrackingNumber</th>
- <th>OrderQty</th>
- <th>ProductID</th>
- <th>UnitPrice</th>
- </tr>
- </tfoot>
- </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.
Now we will create a table.
Create table in database
Below is the query to create table in database.
- USE [TrialsDB]
- GO
-
- /****** Object: Table [dbo].[SalesOrderDetail] Script Date: 19-Feb-16 12:30:55 PM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- CREATE TABLE [dbo].[SalesOrderDetail](
- [SalesOrderID] [int] NOT NULL,
- [SalesOrderDetailID] [int] IDENTITY(1,1) NOT NULL,
- [CarrierTrackingNumber] [nvarchar](25) NULL,
- [OrderQty] [smallint] NOT NULL,
- [ProductID] [int] NOT NULL,
- [SpecialOfferID] [int] NOT NULL,
- [UnitPrice] [money] NOT NULL,
- [UnitPriceDiscount] [money] NOT NULL,
- [LineTotal] AS (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0))),
- [rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
- [ModifiedDate] [datetime] NOT NULL,
- CONSTRAINT [PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID] PRIMARY KEY CLUSTERED
- (
- [SalesOrderID] ASC,
- [SalesOrderDetailID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- 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.
- USE [TrialsDB]
- GO
-
- INSERT INTO [dbo].[SalesOrderDetail]
- ([SalesOrderID]
- ,[CarrierTrackingNumber]
- ,[OrderQty]
- ,[ProductID]
- ,[SpecialOfferID]
- ,[UnitPrice]
- ,[UnitPriceDiscount]
- ,[rowguid]
- ,[ModifiedDate])
- VALUES
- (<SalesOrderID, int,>
- ,<CarrierTrackingNumber, nvarchar(25),>
- ,<OrderQty, smallint,>
- ,<ProductID, int,>
- ,<SpecialOfferID, int,>
- ,<UnitPrice, money,>
- ,<UnitPriceDiscount, money,>
- ,<rowguid, uniqueidentifier,>
- ,<ModifiedDate, datetime,>)
- 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.
- USE [TrialsDB]
- GO
- /****** Object: StoredProcedure [dbo].[usp_Get_SalesOrderDetail] Script Date: 19-Feb-16 12:33:43 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
-
-
-
-
- ALTER PROCEDURE [dbo].[usp_Get_SalesOrderDetail]
- AS
- BEGIN
-
-
- SET NOCOUNT ON;
-
-
- SELECT top(100) SalesOrderID,SalesOrderDetailID,CarrierTrackingNumber,OrderQty,ProductID,UnitPrice,ModifiedDate from dbo.SalesOrderDetail
- 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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using jQuery_Datatable_With_Server_Side_Data.Models;
- namespace jQuery_Datatable_With_Server_Side_Data.Controllers
- {
- public class HomeController: Controller
- {
- TrialsDBEntities tdb;
- Sales sa = new Sales();
- public ActionResult Index()
- {
- return View();
- }
- public JsonResult GetGata()
- {
- try
- {
- using(tdb = new TrialsDBEntities())
- {
- var myList = sa.GetSales(tdb);
- return Json(myList, JsonRequestBehavior.AllowGet);
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
- }
- }
Here
TrialsDBEntities is our entity class. Please note that to use the model classes in your controller, you must add the reference as follows.
- 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 ?.
- public object GetSales(TrialsDBEntities tdb)
- {
- try
- {
- var myList = ((from l in tdb.SalesOrderDetails select new
- {
- SalesOrderID = l.SalesOrderID,
- SalesOrderDetailID = l.SalesOrderDetailID,
- CarrierTrackingNumber = l.CarrierTrackingNumber,
- OrderQty = l.OrderQty,
- ProductID = l.ProductID,
- UnitPrice = l.UnitPrice
- }).OrderBy(l => l.SalesOrderID)).Take(100).ToList();
- return myList;
-
- }
- catch (Exception)
- {
-
- throw new NotImplementedException();
- }
-
- }
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.
- public List < SalesOrderDetail > GetSalesSP(TrialsDBEntities tdb)
- {
- try
- {
- var myList = tdb.Database.SqlQuery < SalesOrderDetail > ("EXEC usp_Get_SalesOrderDetail").ToList();
- return myList;
-
- }
- catch (Exception)
- {
-
- throw new NotImplementedException();
- }
-
- }
Now the only thing pending is to call our controller
JsonResult action, right? We will do some code in our
MyScript.js file.
- $(document).ready(function() {
- $('#myGrid').DataTable({
- "ajax": {
- "url": "../Home/GetGata/",
- "dataSrc": ""
- },
- "columns": [{
- "data": "SalesOrderID"
- }, {
- "data": "SalesOrderDetailID"
- }, {
- "data": "CarrierTrackingNumber"
- }, {
- "data": "OrderQty"
- }, {
- "data": "ProductID"
- }, {
- "data": "UnitPrice"
- }]
- });
- });
Here “
dataSrc”: “” should be used if you have a plain JSON data. The sample data can be seen below.
- [{"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 Figure: jQuery Datatable With Server Side Data
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: