Sending hidden fields in jqGrid

22. May 2010 Uncategorized 0

I’ve just started using jQuery for a website I’m working on. One tool that I have needed is the jqGrid.
I’ve got several places that are helped by displaying a grid. And the basic view function of the grid was fairly straightforward. Especially after following Phil Haack’s tutorial.

However, I also had a few grids where I anticipate the user will need to add a new row. One area in particular is a Farrier History. It’s a horse site and they want to keep track of each time the farrier comes out, and also any notes that he might have had. So we have a horse detail page that contains, among other things, a farrier history.

The structure of the farrier object is basically farrierId, horseId, farrierDate, farrierNotes. The horseId is unique for each horse detail page. That is, if I load the details page for Horse 13, every record on that page needs to be tied to horse 13.

I took a look at a blog on how to add rows. But unfortunately, I still struggled with how to set the horse ID so that the user can’t change it, and preferably they don’t even see it.

It comes down to 3 colModel properties:

  • editable
  • editoptions
  • hidden

The first thing was to set the hidden value to true:

hidden: true

This made sure my user couldn’t see the horse id. However, I was still having problems getting the value passed back to my controller. I then set the editable to true

editable: true

This started passing back a value to my controller. Unfortunately, the value it was passing back was always null, because a value was never set.

The final step was to use editoptions to set a default value.

editoptions: { defaultValue:defVal}

Then all I needed to do was set the jScript variable defVal. To do that, I simply declared:
var defVal = ‘<%= ViewData[“horseId”] %>’;

Now, when the user clicks the “Add Row” button, they are presented with a box for the date, and a box for the notes. HorseId is not shown anywhere, but the controller receives an int? for the horseId value.

The entire script is:
var defVal = <%= ViewData[“horseId”] %>
$(function() {</div>
url: ‘&lt;%= Url.Action(“History”, “Farrier”, new { id = ViewData[“horseId”]}) %&gt;’,
editurl: ‘/Farrier/Add’,
datatype: ‘json’,
mtype: ‘GET’,
colNames: [‘horseId’, ‘date’, ‘notes’],
colModel: [
{ name: ‘horseId’, index: ‘horseId’, width: 250, align: ‘left’, editable: true, editoptions: { defaultValue:defVal}, hidden:true },
{ name: ‘date’, index: ‘farrierDate’, width: 100, align: ‘left’, formatter:’date’, datefmt: ‘mm/dd/yyyy’, editable: true,  editrules: {date:true} },
{ name: ‘notes’, index: ‘farrierNotes’, width: 500, align: ‘left’, editable: true, edittype: ‘textarea’ }</div>
pager: jQuery(‘#pager’),
rowNum: 5,
rowList: [5, 10, 20, 50],
sortname: ‘farrierDate’,
sortorder: “DESC”,
viewrecords: true,
width: 850
jQuery(“#list”).navGrid(‘#pager’, { add: true });</div>