Saturday, August 10, 2019

Implement custom multicolumn server-side filtering in jQuery dataTables

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 3: Custom multicolumn server-side filtering in jQuery DataTables.</h2>
  6. <div style="width:90%; margin:0 auto">
  7. @* Search Area *@
  8. <div style="background-color:#f5f5f5; padding:20px">
  9. <h2>Search Panel</h2>
  10. <table>
  11. <tbody>
  12. <tr>
  13. <td>Employee Name</td>
  14. <td><input type="text" id="txtEmployeeName" /></td>
  15. <td>Country</td>
  16. <td>
  17. <select id="ddCountry" style="width:200px">
  18. <option value="">All Country</option>
  19. <option value="USA">USA</option>
  20. <option value="Poland">Poland</option>
  21. <option value="Finland">Finland</option>
  22. </select>
  23. @* Here I have made this select box with some static data for make this example simpler.
  24. You can fill it from database data *@
  25. </td>
  26. <td>
  27. <input type="button" value="Search" id="btnSearch" />
  28. </td>
  29. </tr>
  30. </tbody>
  31. </table>
  32. </div>
  33. @* jQuery DataTables *@
  34. <div>
  35. <table id="myTable" class="table table-responsive table-striped">
  36. <thead>
  37. <tr>
  38. <th>Employee Name</th>
  39. <th>Company</th>
  40. <th>Phone</th>
  41. <th>Country</th>
  42. <th>City</th>
  43. <th>Postal Code</th>
  44. </tr>
  45. </thead>
  46. </table>
  47. </div>
  48. </div>
  49.  
  50. @* jQuery DataTables css *@
  51. <link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
  52. @* jQuery *@
  53. @section Scripts{
  54. <script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
  55. <script>
  56. $(document).ready(function () {
  57.  
  58. //jQuery DataTables initialization
  59. $('#myTable').DataTable({
  60. "processing": true, // for show processing bar
  61. "serverSide": true, // for process on server side
  62. "orderMulti": false, // for disable multi column order
  63. "dom": '<"top"i>rt<"bottom"lp><"clear">', // for hide default global search box // little confusion? don't worry I explained in the tutorial website
  64. "ajax": {
  65. "url": "/home/LoadData",
  66. "type": "POST",
  67. "datatype": "json"
  68. },
  69. "columns" : [
  70. { "data": "ContactName", "name": "ContactName", "autoWidth": true }, //index 0
  71. { "data": "CompanyName", "name": "CompanyName", "autoWidth": true }, //index 1
  72. { "data": "Phone", "name": "Phone", "autoWidth": true }, //index 2
  73. { "data": "Country", "name": "Country", "autoWidth": true }, //index 3
  74. { "data": "City", "name": "City", "autoWidth": true }, //index 4
  75. { "data": "PostalCode", "name": "PostalCode", "autoWidth": true }, //index 5
  76. ]
  77. });
  78.  
  79. //Apply Custom search on jQuery DataTables here
  80. oTable = $('#myTable').DataTable();
  81. $('#btnSearch').click(function () {
  82. //Apply search for Employee Name // DataTable column index 0
  83. oTable.columns(0).search($('#txtEmployeeName').val().trim());
  84. //Apply search for Country // DataTable column index 3
  85. oTable.columns(3).search($('#ddCountry').val().trim());
  86. //hit search on server
  87. oTable.draw();
  88. });
  89. });
  90. </script>
  91. }
If you already implemented Part 2 of this series, you can see here I have just added 1 extra line in the jQuey DataTables initialization code.

"dom": '<"top"i>rt<"bottom"lp><"clear">'
I have added this line for hide default global search box.

About "dom"

This initialisation variable allows you to specify exactly where in the DOM you want DataTables to inject the various controls it adds to the page.

Confusion ? Don't worry. Please check the below image
Implement custom multicolumn server-side filtering in jQuery dataTables

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

Skip this step if you have already added reference of System.Linq.Dynamic (we had added this on part 2)
Confusion ? Don't worry. Please check the below image
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, sorting and filtering.

  1. [HttpPost]
  2. public ActionResult LoadData()
  3. {
  4. //jQuery DataTables Param
  5. var draw = Request.Form.GetValues("draw").FirstOrDefault();
  6. //Find paging info
  7. var start = Request.Form.GetValues("start").FirstOrDefault();
  8. var length = Request.Form.GetValues("length").FirstOrDefault();
  9. //Find order columns info
  10. var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault()
  11. + "][name]").FirstOrDefault();
  12. var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
  13. //find search columns info
  14. var contactName = Request.Form.GetValues("columns[0][search][value]").FirstOrDefault();
  15. var country = Request.Form.GetValues("columns[3][search][value]").FirstOrDefault();
  16.  
  17. int pageSize = length != null ? Convert.ToInt32(length) : 0;
  18. int skip = start != null ? Convert.ToInt16(start) : 0;
  19. int recordsTotal = 0;
  20.  
  21.  
  22. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  23. {
  24. // dc.Configuration.LazyLoadingEnabled = false; // if your table is relational, contain foreign key
  25. var v = (from a in dc.Customers select a);
  26.  
  27. //SEARCHING...
  28. if (!string.IsNullOrEmpty(contactName))
  29. {
  30. v = v.Where(a=>a.ContactName.Contains(contactName));
  31. }
  32. if (!string.IsNullOrEmpty(country))
  33. {
  34. v = v.Where(a => a.Country == country);
  35. }
  36. //SORTING... (For sorting we need to add a reference System.Linq.Dynamic)
  37. if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
  38. {
  39. v = v.OrderBy(sortColumn + " " + sortColumnDir);
  40. }
  41.  
  42. recordsTotal = v.Count();
  43. var data = v.Skip(skip).Take(pageSize).ToList();
  44. return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data },
  45. JsonRequestBehavior.AllowGet);
  46.  
  47. }
  48. }
If you already implemented part 2 of this series, you can see I have just added few new lines [line no: 13-14 and line no: 27-34]


  1. //find search columns info
  2. var contactName = Request.Form.GetValues("columns[0][search][value]").FirstOrDefault();
  3. var country = Request.Form.GetValues("columns[3][search][value]").FirstOrDefault();
AND
  1. //SEARCHING...
  2. if (!string.IsNullOrEmpty(contactName))
  3. {
  4. v = v.Where(a=>a.ContactName.Contains(contactName));
  5. }
  6. if (!string.IsNullOrEmpty(country))
  7. {
  8. v = v.Where(a => a.Country == country);
  9. }

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 { ...