Column Wise Filter In Web Grid By Jquery Data Table

Introduction
 
The core idea of this article is implementing the column-wise filter in Web Grid. If you are working on MVC, you understand the Web Grid in a very simple way. Basically, Web Grid is used to display the data on a Web page, using an HTML table element. Like ASP.NET Web Forms GridView and DataList, ASP.NET MVC doesn't have any built-in data controls but MVC has Web Grid class handling the same feature using jQuery.
 
Background

For this, you must have basic knowledge of MVC, like how to make the project, how to make a controller, how to make an Action Method, etc.   
 
Filling up the Web Grid

Let's start with filling up Web Grid from the database. First, we have to create an Action Method in the Controller, which returns the collection of data (model).
 
Controller
  1. public ActionResult FillWebGrid()  
  2.        {  
  3.            IEnumerable<WebGridModel> IEWebgrdmdl = ObjAuCon.GetDataInList<WebGridModel>(@"Proc_GetWebgrid");  
  4.            return View(IEWebgrdmdl);  
  5.        } 
What is the code given above?

Actually, I made an Action Method name FillWebGrid() in my Controller, ObjAuCon is a DB layer object, GetDatainList() is a generic method, which is defined in DB layer, which has its list as return type, WebGridModel is a model and IEWebgrdmdl is the IEnumerable container, which I make from WebGridModel and last Proc_GetWebgrid is a stored procedure, which executes and gets the record.
 
This simply gets Web Grid records from the database and returns to the View. 
 
View
  1. @model IEnumerable<Webgrid.Models.WebGridModel> 
Our Action Method returns collection of WebGridModel model, so our View will have the above @model Directive. Now, right click on FillWebGrid action and add a View, which shows your Web Grid and add the line of code given above on View in the top. Afterwards, add the Web Grid, as shown below. 
  1. <div class="table-responsive">  
  2.                     <div id="divGrid">  
  3.                         @if (Model != null && Model.Count() > 0)  
  4.                         {  
  5.                             WebGrid grid = new WebGrid(Model, canPage: false, canSort: false, ajaxUpdateContainerId: "gridContent");  
  6.                             <div id="gridContent1">  
  7.                                 @grid.GetHtml(  
  8.                                  htmlAttributes: new { id = "webgrid" },  
  9.                                  tableStyle: "table table-bordered mdl-data-table",  
  10.                                  fillEmptyRows: false,  
  11.                                  columns: grid.Columns(  
  12.                                  grid.Column(header: "S.No.", format: item => item.WebGrid.Rows.IndexOf(item) + 1 + Math.Round(Convert.ToDecimal(grid.TotalRowCount / grid.PageCount) / grid.RowsPerPage) * grid.RowsPerPage * grid.PageIndex, canSort: true),  
  13.                                  grid.Column("Name", header: "Name"),  
  14.                                  grid.Column("Email", header: "Email"),  
  15.                                  grid.Column("Address", header: "Address")                                 
  16.                                  ))  
  17.   
  18.                             </div>  
  19.                         }  
  20.                         else  
  21.                         {  
  22.                             <div style="width: 100%; text-align: center;" id="gridContent">  
  23.                                 <h4 style="text-align: center; border: 1px solid">No Record Found</h4>  
  24.                             </div>  
  25.                         }  
  26.   
  27.                     </div>  
  28.                 </div> 
This will list the data from the database. Here, I am using a material design theme. You can use simple CSS or Bootstrap also.
 
Afterwards, apply jQuery datatable to your Webgrid (for this, you should need to make design compatible)
 
Here is the jQuery function to initialize the jQuery datatable
  1. $(document).ready(function () {  
  2.         $('#webgrid').DataTable({  
  3.             columnDefs: [  
  4.                 {  
  5.                     targets: [0, 1, 2],  
  6.                     className: 'mdl-data-table__cell--non-numeric'  
  7.                 }  
  8.             ]  
  9.         });  
  10.     }); 
I am using a material design theme, so to initialize the datatable and apply the design, I have to use the jQuery function given above
and the main jquery function is for inititialization is  $('#webgrid').DataTable();
 
Afterwards, your Web Grid looks, as shown below.

 

Here is the code for applying jQuery datatable search column wise.  
  1. $(document).ready(function () {  
  2.         //added the second row in thead   
  3.         var thead = $('<tr class="dt"></tr>');  
  4.         $('#webgrid thead th').each(function (i, r) {  
  5.             var nm = $('#webgrid thead th').eq($(this).index()).text();  
  6.             thead.append('<th></th>');  
  7.         });  
  8.         $('#gridCol thead').append(thead);  
  9.   
  10.         //adding input box in thead second row  
  11.         for (var i = 1; i < $("#webgrid tr:nth-child(2) th").length - 1; i++) {  
  12.             var title = $('#webgrid thead th').eq(i).text();  
  13.             $('#webgrid thead tr:nth-child(n+2) th').eq(i).html("<input type='text' id='" + i + "'  placeholder='" + title + "' >");  
  14.         };  
  15.   
  16.         //apply DataTable  
  17.         var table = $('#webgrid').DataTable();  
  18.   
  19.         //apply dom element to every input box  
  20.         table.columns().eq(0).each(function (colIdx) {  
  21.             debugger  
  22.             $($(this).find("#webgrid thead tr:nth-child(n+2) th input[type='text']")).on('keyup change'function () {//trigger the keyup event  
  23.                 debugger  
  24.                 table  
  25.                     .column(this.id)  
  26.                     .search(this.value.replace(/;/g, "|"), truefalse)  
  27.                     .draw();  
  28.             });  
  29.         });   
  30.        
  31.     }); 
I added the filter column in the thead section of the Web Grid. The Web Grid has a second row of threads, so first make the thread's second row 
 
Now, after adding the code given above, your Web Grid looks as shown below.

Up Next
    Ebook Download
    View all
    Learn
    View all