Thursday, March 22, 2012

Javascript - JQuery Grid – jqGrid with ASP .NET


This article explains how to use jqGrid jQuery plugin to display a Javascript grid control like in the below figure. jqGrid is an Ajax-enabled jQuery plugin to display tabular data.











For the purpose we need to reference jquery.jqGrid.min.js and jquery-1.7.1.min.js libraries and we can do this in the header section of the page as follows.

Header content

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
 <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/redmond/jquery-ui.css" />
 <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript"></script>
 <script src="Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
</asp:Content>


Implementation of the grid is based on storing the grid data in a hidden field as a JSON string. Therefore when a grid row is edited or deleted hidden field content will also updated with RowSaveButtonClick and RowDeleteButtonClick functions respectively. (“gridDataOrderDetials” is the hidden field)

So at the end we can read hidden field value and Deserialize it to a list of objects, in the C# code. 

Here “AddRowDatafunction works as a helper method to build JSON string in row edit and delete.

Body content

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

 <!-- Grid -->
 <table id="JqTableOrderDetails" class="JqTableOrderDetails"></table>
 <!-- HiddenField to store grid JSON data -->
 <asp:HiddenField ID="gridDataOrderDetials" runat="server" />

 <script type="text/javascript">
 // Grid data.
 var orderData = jQuery.parseJSON('[{"ShippingAddress":"Colombo 01","OrderDate":"2011-12-20","OrderId":"100"},{"ShippingAddress":"Colombo 02","OrderDate":"2012-01-15","OrderId":"101"},{"ShippingAddress":"Colombo 03","OrderDate":"2012-02-19","OrderId":"102"}] ');
 
 // Create grid.
 $(function () {
  $(".JqTableOrderDetails").jqGrid({
   datatype: 'local',
   colNames: ['Order Id', 'Order Date', 'Shipping Address', ''],
   colModel: [
     { name: 'OrderId', index: 'OrderId', width: 200, sortable: false },
     { name: 'OrderDate', index: 'OrderDate', width: 200, sortable: false, editable: true, edittype: 'text' },
     { name: 'ShippingAddress', index: 'ShippingAddress', width: 200, sortable: false, editable: true, edittype: 'text' },
     { name: 'action', index: 'action', width: 200 }
     ],
   // Add action buttons
   gridComplete: function () {
    var ids = $(".JqTableOrderDetails").jqGrid('getDataIDs');
    
    for (var i = 0; i < ids.length; i++) {
     edit = "<input id='" + ids[i] + "_Edit' type='button' value='Edit' onclick=\"RowEditButtonClick(" + ids[i] + ")\" />";
     save = "<input id='" + ids[i] + "_Save' type='button' value='Save' onclick=\"RowSaveButtonClick(" + ids[i] + ")\" />";
     erase = "<input id='" + ids[i] + "_Erase' type='button' value='Del' onclick=\"RowDeleteButtonClick(" + ids[i] + ")\" />";
     $(".JqTableOrderDetails").jqGrid('setRowData', ids[i], { action: edit + save + erase });
    }    
   },
   caption: 'Order Details'
  });

  // Load grid data.
  if (orderData != null) {
   for (var i = 0; i < orderData.length; i++) {
    $("#JqTableOrderDetails").jqGrid('addRowData', i, orderData[i], 'last', 0);
   }
  }    
 });

 function RowEditButtonClick(cellId) {
  var ret = $(".JqTableOrderDetails").jqGrid('getRowData', cellId);
  $(".JqTableOrderDetails").restoreRow(cellId);
  $(".JqTableOrderDetails").jqGrid('setRowData', cellId, { OrderId: ret.OrderId, OrderDate: ret.OrderDate, ShippingAddress: ret.ShippingAddress });
  $(".JqTableOrderDetails").editRow(cellId, false);
 }

 function RowSaveButtonClick(cellId) {
  var ret = $(".JqTableOrderDetails").jqGrid('getRowData', cellId);
  
  $(".JqTableOrderDetails").jqGrid('setRowData', cellId, { OrderId: getCellDataValue(ret.OrderId), OrderDate: getCellDataValue(ret.OrderDate), ShippingAddress: getCellDataValue(ret.ShippingAddress) });
  $('#gridDataOrderDetials').attr('value', '[' + AddRowData($(".JqTableOrderDetails").jqGrid('getRowData', cellId), cellId) + ']');
 }

 function RowDeleteButtonClick(cellId) {
  $(".JqTableOrderDetails").delRowData(cellId);
  $('#gridDataOrderDetials').attr('value', '[' + AddRowData($(".JqTableOrderDetails").jqGrid('getRowData', cellId), cellId) + ']');
 }

 var rowDataGrid = new Array();
 function AddRowData(arr, cellId) {
  var memberArr = new Array();
  memberArr[0] = 'OrderId';
  memberArr[1] = 'OrderDate';
  memberArr[2] = 'ShippingAddress';
  selectRow = JSON.stringify(arr, memberArr);
  rowDataGrid[cellId] = selectRow;
  var ids = $(".JqTableOrderDetails").jqGrid('getDataIDs');
  var outData;
  var first = true;
  for (var i = 0; i < ids.length; i++) {
   if (rowDataGrid[ids[i]] != undefined) {
    if (first) {
     outData = rowDataGrid[ids[i]];
     first = false;
    }
    else {
     outData = outData + "," + rowDataGrid[ids[i]];
    }
   }
  }
  return outData;
 } 
 
 function getCellDataValue(rowValue) {
  if ($(rowValue).val() != null) {
   return $(rowValue).val();
  }
  else {
   return rowValue;
  }
 }
 </script>
</asp:Content>

Here are few jQuery grid plugins can be found in the web.
  • Flexigrid: http://flexigrid.info/
  • jQuery Grid: http://www.trirand.com/blog/
  • Ingrid: http://reconstrukt.com/ingrid/
  • SlickGrid http://github.com/mleibman/SlickGrid
  • DataTables http://www.datatables.net/index