14 June 2015

Working with local data in jqgrid

Recently I helped a friend of mine on Jqgrid. He was trying to build a page, which had multiple tabs and some tabs had grid user interface, to add, edit and delete rows. JQGRID fitted his requirement nicely. Only on submission of the entire form he wanted to post data, until then rows added, edited should be maintained locally in the browser.

There are many E2E sample available in internet on jqgrid working with server API, but we couldn’t find any single E2E solution in jqgrid working with local data.

In this post let’s see how did we get jqgrid to work with local data - explaining adding a row, editing a row and deleting a row and with all the data stored in a JSON object locally.

JSON data structure in question

var customersData= [
{id: guid(), FirstName: "Ranga", LastName: "H C", sendEmail: true },
{id: guid(), FirstName: "Vijay", LastName: "Kumar", sendEmail: true },
{id: guid(), FirstName: "Praveen", LastName: "C", sendEmail: true }];

It’s a JSON array of customers. Each customer representing a auto generated unique id, first name, last name and email subscription option.

Screenshot showing the Grid in action

jqgrid tutorial working with local data

ASP.MVC application view to display the customer grid

<div id="gridPager"></div>
<table id="customerGrid"></table>

JavaScript code using jqgrid

Let's go through the most important java-script code to setup the jqgrid working with local JSON data.

Settig up the jqgrid

Inside the $(document).ready() function add the below code.Highlights of the below code:

  1. In the jqgrid, datatype has been set to ‘local’, indicating JQGrid should work with local data.
  2. data, has been set customersData, which is a JSON data.
  3. Uses the custome guid() function to get unique identifier for the row.
var customersData = [
{ id: guid(), FirstName: "Ranga", LastName: "H C", sendEmail: true },
{ id: guid(), FirstName: "Vijay", LastName: "Kumar", sendEmail: true },
{ id: guid(), FirstName: "Praveen", LastName: "C", sendEmail: true }];

$("#customerGrid").jqGrid({
 datatype: 'local',
 data: customersData,
 colNames: ['id', 'FirstName', 'LastName', 'sendEMail'],
 colModel: [
  { name: 'id', index: 'id', width: 90, hidden: true },
  {
  name: 'FirstName', index: 'FirstName', width: 120, 
  editable: true,
  editrules: { required: true }
  },
  {
  name: 'LastName', index: 'LastName', width: 120, 
  editable: true,
  editrules: { required: true }
  },
  {
  name: 'sendEmail', index: 'sendEmail',
  width: 90, align: 'center',
  formatter: 'checkbox', editrules: { required: true },
  edittype: 'checkbox', editoptions: { value: 'Yes:No',   
defaultValue: 'Yes' },
  editable: true
  }],
    gridview: true,
    rownumbers: false,
    pager: '#gridPager',
    height: '100%',
    rowList: [],       //
    pgbuttons: false,  // 
    pgtext: null,      // Disable pagination options
    viewrecords: false // 
    });

beforeSubmit function

While working with the local data, the logic of reading the posted data should in place before submitting the details into server API. Hence the beforeSubmit() function is the right place put such logic and also note that, fields validation will also trigger set validation rules set will also be functional.

beforeSubmit function in the add row option

Highlights of the beforeSubmit code.
  1. Get’s submitted form data using postdata parameter.
  2. Creates the unique customer id using the guid() method.
  3. Adds the customer JSON data to the customersData using the JSON array push method.
  4. Refreshes the jqgrid, so that newly added customer row is visible in the grid.
  5. Closes the ‘Add Record’ dialog box using the click trigger on the close button.This action results in exception, so eat the exception. This is not clean solution to close the dialog!
beforeSubmit: function (postdata, formid) {
customersData.push({ id: guid(), FirstName: postdata.FirstName,
LastName: postdata.LastName, sendEmail: postdata.sendEmail });

$('#customerGrid').jqGrid('setGridParam', { datatype: 'local',
 data: customersData }).trigger('reloadGrid');

try {
$(".ui-icon-closethick").trigger('click');
}
catch (ex) { }
return [false, ''];
}

beforeSubmit function in the edit row option

Highlights of the beforeSubmit code:
  1. Identify the id of the record being edited.
  2. Identity the index of the record in the JSON array.
  3. Builds the updated customer JSON object data using the submitted form data.
  4. Uses the JSON splice() method to insert the edited JSON object at the same position as the original customer object in the array
  5. Refreshes the jqgrid, so that edited customer row values are visible.
  6. Closes the ‘Edit Record’ dialog box using the click trigger on the close button. This action results in exception, so eat the exception.
beforeSubmit: function (postdata, formid) {

var myGrid = $('#customerGrid');
var selRowId = myGrid.jqGrid('getGridParam', 'selrow');
var rowGuid = myGrid.jqGrid('getCell', selRowId, 'id');

var dataIndex = undefined;

$.each(customersData, function (index, value) {
if (value.id === rowGuid) {
dataIndex = index;
}
});

if (dataIndex != undefined) {
customersData.splice(dataIndex, 1, 
{ id: rowGuid, FirstName: postdata.FirstName, 
LastName:postdata.LastName, sendEmail: postdata.sendEmail });
}

$('#customerGrid').jqGrid('setGridParam',
{ datatype: 'local', data: customersData }).
      trigger('reloadGrid');

try {
$(".ui-icon-closethick").trigger('click');
}
catch (ex) { }
return [false, ''];
});

beforeSubmit function in the delete row option

Highlights of the beforeSubmit code:
  1. Identify the id of the record being removed.
  2. Identify the index of the record in the JSON array.
  3. Uses the JSON splice() method to remove the selected record from the JSON array data.
  4. Invokes the delRowData() to delete the row the jqgrid. Refreshing grid didn’t here!
  5. Closes the ‘Edit Record’ dialog box using the click trigger on the close button. This action results in exception, so eat the exception.
beforeSubmit: function (postdata, formid) {

var myGrid = $('#customerGrid');
var selRowId = myGrid.jqGrid('getGridParam', 'selrow');
var rowGuid = myGrid.jqGrid('getCell', selRowId, 'id');

var dataIndex = undefined;

$.each(customersData, function (index, value) {
 if (value.id === rowGuid) {
       dataIndex = index;
    }
   });

if (dataIndex != undefined) {
customersData.splice(dataIndex, 1);
}

$('#customerGrid').delRowData(selRowId);

try {
$(".ui-icon-closethick").trigger('click');
}
catch (ex) {
console.log(ex);
}
return [false, ''];
}

At end of the operations, the customersData JSON array holds latest of data added, edited and deleted. You can use JSON.stringfy() method to covert JSON data into string and post the string value to the server.

ASP.NET MVC application's packages.config file

Use the below info to identify frameworks version being used.

<packages>
  <package id="Antlr" version="3.4.1.9004" 
          targetFramework="net451" />
  <package id="bootstrap" version="3.0.0" 
          targetFramework="net451" />
  <package id="jQuery" version="1.10.2" 
          targetFramework="net451" />
  <package id="jQuery.UI.Combined" version="1.8.11" 
          targetFramework="net451" />
  <package id="jQuery.Validation" version="1.11.1" 
          targetFramework="net451" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.2" 
          targetFramework="net451" />
  <package id="Microsoft.AspNet.Razor" version="3.2.2" 
          targetFramework="net451" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3"
          targetFramework="net451" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.2" 

  targetFramework="net451" />
  <package id="Microsoft.jQuery.Unobtrusive.Validation" 
     version="3.2.2" targetFramework="net451" />
  <package id="Microsoft.Web.Infrastructure" 

   version="1.0.0.0" targetFramework="net451" />
  <package id="Modernizr" version="2.6.2" targetFramework="net451" />
  <package id="Newtonsoft.Json" version="6.0.4" 
               targetFramework="net451" />
  <package id="Respond" version="1.2.0" 
               targetFramework="net451" />
  <package id="Trirand.jqGrid" version="4.6.0" 
               targetFramework="net451" />
  <package id="WebGrease" version="1.5.2" 
               targetFramework="net451" />
</packages>

Your comments are welcome!

No comments:

Post a Comment