Saturday, August 10, 2019

jQuery Datatable server side pagination and sorting in ASP.NET MVC

Step-1: Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Basic > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.
Here I have added a database for store some location information in our database for show in the google map.

Step-3: Create a table.

Here I will create 1 table (as below) for store data.
Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used 1 table as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >


Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller "HomeController"

Step-6: Add new action into the controller to get the view where we will implement jQuery DataTable with server-side paging and sorting.

Here I have added "Index" Action into "Home" Controller. Please write this following code
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

Step-7: Add view for the action (here "Index") & design.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
Complete HTML code 
  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4.  
  5. <h2>Part 2: jQuery DataTable server side pagination and sorting in asp.net MVC</h2>
  6. <div style="width:90%; margin:0 auto;">
  7. <table id="myTable">
  8. <thead>
  9. <tr>
  10. <th>Employee Name</th>
  11. <th>Company</th>
  12. <th>Phone</th>
  13. <th>Country</th>
  14. <th>City</th>
  15. <th>Postal Code</th>
  16. </tr>
  17. </thead>
  18. </table>
  19. </div>
  20.  
  21. @* Load datatable css *@
  22. <link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
  23. @section Scripts{
  24. @* Load DataTable js here *@
  25. <script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
  26. <script>
  27. $(document).ready(function () {
  28. $("#myTable").DataTable({
  29. "processing": true, // for show progress bar
  30. "serverSide": true, // for process server side
  31. "filter": false, // this is for disable filter (search box)
  32. "orderMulti": false, // for disable multiple column at once
  33. "ajax": {
  34. "url": "/home/LoadData",
  35. "type": "POST",
  36. "datatype": "json"
  37. },
  38. "columns": [
  39. { "data": "ContactName", "name": "ContactName", "autoWidth": true },
  40. { "data": "CompanyName", "name": "CompanyName", "autoWidth": true },
  41. { "data": "Phone", "name": "Phone", "autoWidth": true },
  42. { "data": "Country", "name": "Country", "autoWidth": true },
  43. { "data": "City", "name": "City", "autoWidth": true },
  44. { "data": "PostalCode", "name": "PostalCode", "autoWidth": true }
  45. ]
  46. });
  47. });
  48. </script>
  49. }
  50.  

Step-8: Add reference of System.Linq.Dynamic

Here I have added System.Linq.Dynamic reference from NuGet packages
Go to Solution Explorer > Right click on References > Manage NuGet packages > Search with "System.Linq.Dynamic" > Install.

Step-9: Add another action (here "LoadData") for fetch data from the database and implement logic for server side paging and sorting.

  1. [HttpPost]
  2. public ActionResult LoadData()
  3. {
  4.  
  5. var draw = Request.Form.GetValues("draw").FirstOrDefault();
  6. var start = Request.Form.GetValues("start").FirstOrDefault();
  7. var length = Request.Form.GetValues("length").FirstOrDefault();
  8. //Find Order Column
  9. var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
  10. var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
  11.  
  12.  
  13. int pageSize = length != null? Convert.ToInt32(length) : 0;
  14. int skip = start != null ? Convert.ToInt32(start) : 0;
  15. int recordsTotal = 0;
  16. using (MyDatatableEntities dc = new MyDatatableEntities())
  17. {
  18. // dc.Configuration.LazyLoadingEnabled = false; // if your table is relational, contain foreign key
  19. var v = (from a in dc.Customers select a);
  20.  
  21. //SORT
  22. if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
  23. {
  24. v = v.OrderBy(sortColumn + " " + sortColumnDir);
  25. }
  26.  
  27. recordsTotal = v.Count();
  28. var data = v.Skip(skip).Take(pageSize).ToList();
  29. return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
  30. }
  31. }

Step-10: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...