Working With JQX Grid With Filtering And Sorting And Searching

Introduction

We have all worked with JQ Grid. Today I got a requirement to implement JQX Grid in my web application. If you are new to JQ Grid you can read about it here: Using JqGrid in ASP.NET. Here I will explain how to implement JQX Grid in our application.

 
This article has been selected as Asp.Net Community Article of the Day Tuesday, December 30, 2014 (Working with JQX Grid with Filtering and Sorting and Searching)

What you must know
  1. jQuery : What is jQuery? 
  2. JavaScript : JavaScript Tutorial
  3. CSS 3 : CSS3 Introduction 
  4. HTML : HTML(5) Tutorial 
  5. DOM Manipulations in jQuery : jQuery - DOM Manipulation Methods

Background

We can implement the JQX Grid in MVC and in our web application. You can find the demo here: jqxGrid.

You can download the necessary file from http://www.jqwidgets.com/download/.

What made me choose JQX Grid

What made me choose JQX Grid? The answer is simple. We have so many client-side grid providers (JQGrid, Telerik, JQX and so on). If you are not aware of those, please have a look at: http://www.sitepoint.com/10-jquery-grids/

But for my requirements the client needs a toggle panel in which the filtering conditions occur. When I searched, JQX Grid has the best performance. (Some others support the same features, but they were a little slow.)

Using the code

There is a procedure we must follow to implement the JQX in our application.

Step 1

Download all the necessary files.

Step 2

Create a new web application.



Step 3

Add the selected folders to your application.


Step 4

Add a new page.

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4. </head>  
  5. <body >  
  6.   
  7. </body>  
  8. </html> 

Step 5

Add the stylesheets and necessary JavaScript files.

  1. <link rel="stylesheet" href="jqwidgets/styles/jqx.base.css" type="text/css" />  
  2.     <script type="text/javascript" src="scripts/jquery-1.11.1.min.js"></script>  
  3.     <script type="text/javascript" src="jqwidgets/jqxcore.js"></script>  
  4.     <script type="text/javascript" src="jqwidgets/jqxdata.js"></script>  
  5.     <script type="text/javascript" src="jqwidgets/jqxbuttons.js"></script>  
  6.     <script type="text/javascript" src="jqwidgets/jqxscrollbar.js"></script>  
  7.     <script type="text/javascript" src="jqwidgets/jqxlistbox.js"></script>  
  8.     <script type="text/javascript" src="jqwidgets/jqxdropdownlist.js"></script>  
  9.     <script type="text/javascript" src="jqwidgets/jqxmenu.js"></script>  
  10.     <script type="text/javascript" src="jqwidgets/jqxgrid.js"></script>  
  11.     <script type="text/javascript" src="jqwidgets/jqxgrid.filter.js"></script>  
  12.     <script type="text/javascript" src="jqwidgets/jqxgrid.sort.js"></script>  
  13.     <script type="text/javascript" src="jqwidgets/jqxgrid.selection.js"></script>  
  14.     <script type="text/javascript" src="jqwidgets/jqxpanel.js"></script>  
  15.     <script type="text/javascript" src="jqwidgets/jqxcheckbox.js"></script>  
  16.     <script type="text/javascript" src="scripts/demos.js"></script> 

(Make sure that you add the JavaScript files in order.)

Step 6

Create the DOM elements in which you want to show the JQX Grid.

  1. <div id='jqxWidget' style="font-size: 13px; font-family: Verdana; float: left;">  
  2.        <div id="jqxgrid">  
  3.        </div>          
  4.    </div> 

Step 7

Generate some dynamic JSON data so that you can easily generate the JQX Grid. You can get the data from the database and convert it to JSON. If you are unfamiliar with how to convert JSON then you can get it here: Json.NET 6.0.6.

If you are not aware of how to add the newtonsoft and use it then please see this video. And please dont forget to rate his video. He has done good a job :).

JSON Serialization and DeSerialization 

Here I am generating data dynamically in a JavaScript file. Please find the generatedata.js file in the bundle of the JQX Grid. Please add this to your script section.

  1. <script src="generatedata.js" type="text/javascript"></script> 

If you go into the generatedata.js, you can see a function generatedata, that is for creating the data (JSON array) dynamically .

  1. function generatedata(rowscount, hasNullValues) {  
  2.     // prepare the data  
  3.     var data = new Array();  
  4.     if (rowscount == #ff0000) rowscount = 100;  
  5.     var firstNames =  
  6.     [  
  7.         "Andrew""Nancy""Shelley""Regina""Yoshi""Antoni""Mayumi""Ian""Peter""Lars""Petra""Martin""Sven""Elio""Beate""Cheryl""Michael""Guylene"  
  8.     ];  
  9.   
  10.     var lastNames =  
  11.     [  
  12.         "Fuller""Davolio""Burke""Murphy""Nagase""Saavedra""Ohno""Devling""Wilson""Peterson""Winkler""Bein""Petersen""Rossi""Vileid""Saylor""Bjorn""Nodier"  
  13.     ];  
  14.   
  15.     var productNames =  
  16.     [  
  17.         "Black Tea""Green Tea""Caffe Espresso""Doubleshot Espresso""Caffe Latte""White Chocolate Mocha""Caramel Latte""Caffe Americano""Cappuccino""Espresso Truffle""Espresso con Panna""Peppermint Mocha Twist"  
  18.     ];  
  19.   
  20.     var priceValues =  
  21.     [  
  22.          "2.25""1.5""3.0""3.3""4.5""3.6""3.8""2.5""5.0""1.75""3.25""4.0"  
  23.     ];  
  24.   
  25.     for (var i = 0; i < rowscount; i++) {  
  26.         var row = {};  
  27.         var productindex = Math.floor(Math.random() * productNames.length);  
  28.         var price = parseFloat(priceValues[productindex]);  
  29.         var quantity = 1 + Math.round(Math.random() * 10);  
  30.   
  31.         row["id"] = i;  
  32.         row["available"] = productindex % 2 == 0;  
  33.         if (hasNullValues == true) {  
  34.             if (productindex % 2 != 0) {  
  35.                 var random = Math.floor(Math.random() * rowscount);  
  36.                 row["available"] = i % random == 0 ? null : false;  
  37.             }  
  38.         }  
  39.         row["firstname"] = firstNames[Math.floor(Math.random() * firstNames.length)];  
  40.         row["lastname"] = lastNames[Math.floor(Math.random() * lastNames.length)];  
  41.         row["name"] = row["firstname"] + " " + row["lastname"];  
  42.         row["productname"] = productNames[productindex];  
  43.         row["price"] = price;  
  44.         row["quantity"] = quantity;  
  45.         row["total"] = price * quantity;  
  46.   
  47.         var date = new Date();  
  48.         date.setFullYear(2014, Math.floor(Math.random() * 12), Math.floor(Math.random() * 27));  
  49.         date.setHours(0, 0, 0, 0);  
  50.         row["date"] = date;  
  51.          
  52.         data[i] = row;  
  53.     }  
  54.   
  55.     return data;  

Step 8: Now here is the main part. Add the main code to your script tag in the page. Here we are appending the Grid to the element that has the id jqxgrid.

  1. <script type="text/javascript">  
  2.         $(document).ready(function () {  
  3.             var data = generatedata(500);  
  4.             var source =  
  5.             {  
  6.                 localdata: data,  
  7.                 datafields:  
  8.                 [  
  9.                     { name: 'firstname', type: 'string' },  
  10.                     { name: 'lastname', type: 'string' },  
  11.                     { name: 'productname', type: 'string' },  
  12.                     { name: 'date', type: 'date' },  
  13.                     { name: 'quantity', type: 'number' }  
  14.                 ],  
  15.                 datatype: "array"  
  16.             };  
  17.   
  18.             var addfilter = function () {  
  19.                 var filtergroup = new $.jqx.filter();  
  20.   
  21.                 var filter_or_operator = 1;  
  22.                 var filtervalue = 'Beate';  
  23.                 var filtercondition = 'contains';  
  24.                 var filter1 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);  
  25.   
  26.                 filtervalue = 'Andrew';  
  27.                 filtercondition = 'contains';  
  28.                 var filter2 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);  
  29.   
  30.                 filtergroup.addfilter(filter_or_operator, filter1);  
  31.                 filtergroup.addfilter(filter_or_operator, filter2);  
  32.                 // add the filters.  
  33.                 $("#jqxgrid").jqxGrid('addfilter''firstname', filtergroup);  
  34.                 // apply the filters.  
  35.                 $("#jqxgrid").jqxGrid('applyfilters');  
  36.             }  
  37.             var dataAdapter = new $.jqx.dataAdapter(source);  
  38.   
  39.             $("#jqxgrid").jqxGrid(  
  40.             {  
  41.                 width: 850,  
  42.                 source: dataAdapter,  
  43.                 filterable: true,  
  44.                 sortable: true,  
  45.                 autoshowfiltericon: true,  
  46.                 ready: function () {  
  47.                     addfilter();  
  48.                     var localizationObject = {  
  49.                         filterstringcomparisonoperators: ['contains''does not contain'],  
  50.                         // filter numeric comparison operators.  
  51.                         filternumericcomparisonoperators: ['less than''greater than'],  
  52.                         // filter date comparison operators.  
  53.                         filterdatecomparisonoperators: ['less than''greater than'],  
  54.                         // filter bool comparison operators.  
  55.                         filterbooleancomparisonoperators: ['equal''not equal']  
  56.                     }  
  57.                     $("#jqxgrid").jqxGrid('localizestrings', localizationObject);  
  58.                 },  
  59.                 updatefilterconditions: function (type, defaultconditions) {  
  60.                     var stringcomparisonoperators = ['CONTAINS''DOES_NOT_CONTAIN'];  
  61.                     var numericcomparisonoperators = ['LESS_THAN''GREATER_THAN'];  
  62.                     var datecomparisonoperators = ['LESS_THAN''GREATER_THAN'];  
  63.                     var booleancomparisonoperators = ['EQUAL''NOT_EQUAL'];  
  64.                     switch (type) {  
  65.                         case 'stringfilter':  
  66.                             return stringcomparisonoperators;  
  67.                         case 'numericfilter':  
  68.                             return numericcomparisonoperators;  
  69.                         case 'datefilter':  
  70.                             return datecomparisonoperators;  
  71.                         case 'booleanfilter':  
  72.                             return booleancomparisonoperators;  
  73.                     }  
  74.                 },  
  75.                 updatefilterpanel: function (filtertypedropdown1, filtertypedropdown2, filteroperatordropdown, filterinputfield1, filterinputfield2, filterbutton, clearbutton,  
  76.                  columnfilter, filtertype, filterconditions) {  
  77.                     var index1 = 0;  
  78.                     var index2 = 0;  
  79.                     if (columnfilter != null) {  
  80.                         var filter1 = columnfilter.getfilterat(0);  
  81.                         var filter2 = columnfilter.getfilterat(1);  
  82.                         if (filter1) {  
  83.                             index1 = filterconditions.indexOf(filter1.comparisonoperator);  
  84.                             var value1 = filter1.filtervalue;  
  85.                             filterinputfield1.val(value1);  
  86.                         }  
  87.   
  88.                         if (filter2) {  
  89.                             index2 = filterconditions.indexOf(filter2.comparisonoperator);  
  90.                             var value2 = filter2.filtervalue;  
  91.                             filterinputfield2.val(value2);  
  92.                         }  
  93.                     }  
  94.   
  95.                     filtertypedropdown1.jqxDropDownList({ autoDropDownHeight: true, selectedIndex: index1 });  
  96.                     filtertypedropdown2.jqxDropDownList({ autoDropDownHeight: true, selectedIndex: index2 });  
  97.                 },  
  98.                 columns: [  
  99.                   { text: 'First Name', datafield: 'firstname', width: 200 },  
  100.                   { text: 'Last Name', datafield: 'lastname', width: 200 },  
  101.                   { text: 'Product', datafield: 'productname', width: 180 },  
  102.                   { text: 'Order Date', datafield: 'date', width: 160, cellsformat: 'dd-MMMM-yyyy' },  
  103.                   { text: 'Quantity', datafield: 'quantity', cellsalign: 'right' }  
  104.                 ]  
  105.             });  
  106.   
  107.             $('#events').jqxPanel({ width: 300, height: 80});  
  108.   
  109.             $("#jqxgrid").on("filter", function (event) {  
  110.                 $("#events").jqxPanel('clearcontent');  
  111.                 var filterinfo = $("#jqxgrid").jqxGrid('getfilterinformation');  
  112.   
  113.                 var eventData = "Triggered 'filter' event";  
  114.                 for (i = 0; i < filterinfo.length; i++) {  
  115.                     var eventData = "Filter Column: " + filterinfo[i].filtercolumntext;  
  116.                     $('#events').jqxPanel('prepend''<div style="margin-top: 5px;">' + eventData + '</div>');  
  117.                 }  
  118.             });  
  119.   
  120.             $('#clearfilteringbutton').jqxButton({ theme: theme });  
  121.             $('#filterbackground').jqxCheckBox({ checkedtrue, height: 25});  
  122.             $('#filtericons').jqxCheckBox({ checkedfalse, height: 25});  
  123.             // clear the filtering.  
  124.             $('#clearfilteringbutton').click(function () {  
  125.                 $("#jqxgrid").jqxGrid('clearfilters');  
  126.             });  
  127.             // show/hide filter background  
  128.             $('#filterbackground').on('change', function (event) {  
  129.                 $("#jqxgrid").jqxGrid({ showfiltercolumnbackground: event.args.checked });  
  130.             });  
  131.             // show/hide filter icons  
  132.             $('#filtericons').on('change', function (event) {  
  133.                 $("#jqxgrid").jqxGrid({ autoshowfiltericon: !event.args.checked });  
  134.             });  
  135.         });  
  136.     </script> 

Step 9: Now build and run your code, you will get output as in the following:



Have a happy coding :)

History

First version on: 13-Oct-2014 10:30 PM.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now