Editing in jqGrid with asp.net mvc

2009 May 2
by ericdotnet

Phil Haack already posted how to use the jQuery grid ‘jqgrid’ on his blog haacked.com. What wasn’t covered in that tutorial was editing, so I thought it would be nice to add that here.

To be honest it gave me a bit of a headache, as I had created a sample table that had the ID column as primary key/autonumber field and jqgrid posts back an ID as well. Mind you, that is the ROWID and not the ID of your record. In a demo app. this can easily go unnoticed as those two are the same when you just add a few records.

After reading up in the docs, and trying to add an extra parameter to the save call (which accidently broke the whole grid), I simply added a hidden column that contains the primary key.

The table I used for this demo was a simple Employees table with an id, first and lastname.

Here’s what the javascript looks like:

   jQuery("#list").jqGrid({
      url: '/GridDemo/GetGridData',
      datatype: 'json',
      mtype: 'GET',
      colNames: ['IdNr','Id', 'FirstName', 'LastName'],
      colModel: [
          { name: 'IdNr', index: 'IdNr', width: 40, align: 'left',
              editable: true, editrules: { edithidden: true }, hidden: true },
          { name: 'Id', index: 'Id', width: 40, align: 'left',
              editable: false },
          { name: 'FirstName', index: 'FirstName', width: 200, align: 'left', editable: true, edittype: 'text', editoptions: { size: 20, maxlength: 30} },
          { name: 'LastName', index: 'LastName', width: 300, align: 'left', editable: true, edittype: 'text', editoptions: { size: 20, maxlength: 30}}],
      onSelectRow: function(id) {
        if (id && id !== lastsel2) {
          jQuery('#list').restoreRow(lastsel2);
          jQuery('#list').editRow(id, true);
          lastsel2 = id;
        }
      },
      editurl: "/GridDemo/GridSave",
      pager: jQuery('#pager'),
      rowNum: 10,
      rowList: [5, 10, 20, 50],
      sortname: 'Id',
      sortorder: "desc",
      viewrecords: true,
      imgpath: '/content/themes/steel/images',
      caption: 'Employees'
    });
  });     

The IdNr is the hidden field, with the edithidden: true editrules you make sure it gets posted once a row has been edited. I choose for inline editing, there are other forms of editing in the jqgriddocs.

As you can see the editurl is where the data that has been edited will be posted to. That controller action looks like this (using linq2sql, but ofcourse any type of model will do) :

public ActionResult GridSave(int id,int idnr, string firstName, string lastName)
{
  jQueryGridModelDataContext db = new jQueryGridModelDataContext();

  Employee e = db.Employees.SingleOrDefault(p => p.ID == idnr);
  if (!(e == null))
  {
      e.FirstName = firstName;
      e.LastName = lastName;
      db.SubmitChanges();
      return Content("true");
  }
  else
  {
      return Content("false");
  }
}

And that’s it, your grid now has editing functionality ! Ofcourse some validation is required in the GridSave function. The javascript could use the callback function after saving and check for the true or false that gets returned from the GridSave action.

Let me know in the comments if you have any questions or if I made some sort of horrible mistake :) .

kick it on DotNetKicks.com

14 Responses leave one →
  1. 2009 May 4
    mike johnson permalink

    thanks for this. any information like this is helpful until the mass of MVC books arrive.

  2. 2009 May 4

    JqGrid will use your id value as its internal ID if you tell it to, by configuring the jsonReader. I demonstrate how to do that in this blog post:

    http://blogs.teamb.com/craigstuntz/2009/04/15/38212/

    Making this change prevents you from having to distinguish between the actual identity value for the row and the internal ID for the grid.

  3. 2009 May 4

    Oh nice, thanks. I guess you ran into the same problem then ;) .

  4. 2009 May 5

    Nice work!

    But I have to say that the code looks ugly!

    • 2009 May 5

      You mean the javascript part of the save to database part ? The save to db code was just to show how the parameters come into the control. If you mean the js-part I fully agree :) . Not quite sure how you could make that look better tbh !

  5. 2009 May 5

    Hi,

    I meant the JQuery part (JavaScript). Yeah! you are right! Not sure how to improve it further.

    • 2009 May 5

      The first thing I’d suggest for cleaning up the JavaScript is to extract the in-line declaration of onSelectRow into a separate function. The second thing I’d suggest is to only specify the options necessary for this specific grid in that method, and use the setGridDefaults method to set the options used for all grids in your application. That should cut the length of the JavaScript in question in half, at the very least.

  6. 2009 May 8
    jay permalink

    I am trying to populate a select list (combo-box) from a query/url.
    The field I am editing has a edittype:select
    Here is a sample of what I am passing into the colModel of jqGrid.

    colModel :[
    {name:'id',index:'id',hidden:true, width:0,resizable:true, sorttype:"int",editrules:{readonly:true}},
    {name:'name',index:'name', width:300,resizable:true, align:"left",sorttype:"text",editable:true,edittype:"text",editoptions:{size:30,maxlength:50},editrules:{required:true}},
    {name:'valstr',index:'valstr', width:400,resizable:true, align:"left",sorttype:"text",editable:true,edittype:"text",editoptions:{size:30,maxlength:50},editrules:{required:true}},
    {name:'seqnum',index:'seqnum', width:100,resizable:true, align:"left",sorttype:"int",editable:true,edittype:"select",editoptions:{value:"1:one;2:two"},editrules:{required:true}}
    ]

    Notice the last field has edittype:select and value is hard-coded. I want to make the editoptions values populated from a query/url.

    Any suggestions will be appreciated.

    • 2009 May 8

      My guess would be that you could pass in a function into the editoptions values list, that retrieves the values from an url ? Haven’t tried this yet though.

      Would be a good question for stackoverflow.com :) .

  7. 2009 August 7

    For those interested I’ve made a fully working downloadable package available for free at

    http://www.jqgrid.com

    Cheers!

  8. 2009 August 13

    Hi,

    Nice article, but I wish to use jqgrid as client side editting only. So I leave the editURl empty string. In my submit I want among others get the data from the grid together with other data elements in my action. If I leave the value as is (0) I have no problems. Hoewever, when I edit the value and submit the form, I get the message that a potential dangerous message is attempted. Anyone been there, done that?

  9. 2009 October 22
    Kaleem Khan permalink

    I need to add an image column to this grid? and then I want to make a row item (not entire row) cliclable and make it look like underlined (href). are these things possible?

  10. 2009 May 5

    @Craig Thanks for the suggestions, I’ll look into that soon. Think I got the code from the official docs.

Trackbacks & Pingbacks

  1. Dew Drop - May 5, 2009 | Alvin Ashcraft's Morning Dew

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS