Skip to content

Editing in jqGrid with mvc

May 2, 2009

Phil Haack already posted how to use the jQuery grid ‘jqgrid’ on his blog 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:

   var lastsel;
      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 !== lastsel) {
          jQuery('#list').editRow(id, true);
          lastsel = 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;
      return Content("true");
      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

  1. mike johnson permalink
    May 4, 2009 2:55 pm

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

  2. May 4, 2009 3:20 pm

    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:

    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. May 4, 2009 9:02 pm

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

  4. May 5, 2009 9:19 pm

    Nice work!

    But I have to say that the code looks ugly!

    • May 5, 2009 10:02 pm

      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. May 5, 2009 10:27 pm


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

    • May 5, 2009 10:33 pm

      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.

    • May 5, 2009 10:41 pm

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

  6. jay permalink
    May 8, 2009 6:40 pm

    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.

    • May 8, 2009 9:04 pm

      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 :).

    • MeghanaK permalink
      September 17, 2010 9:36 pm

      HI, did you got a solution for populating select list (combo-box) from a query/url


    • Ravi permalink
      December 1, 2010 8:22 am

      Did you got any suggestion for this .. I need to implement the same thing
      Can u please help me

      Thanks and regards

  7. August 7, 2009 10:41 pm

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


  8. August 13, 2009 2:08 pm


    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. Kaleem Khan permalink
    October 22, 2009 6:48 pm

    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. Rohi permalink
    February 2, 2010 11:22 am

    I dont undertand what is ‘lastsel2’ here?
    I run this code I got an Jscript runtime error.

    • February 2, 2010 11:53 am

      You have to define var lastsel2; outside of the jqgrid part. It remembers which row you selected last.

      I’ll edit the code, it seems I have forgotten to put that in here.

  11. Twaldron permalink
    April 6, 2010 5:18 pm

    I wish you would show the GetGridDataController so we could see how you are using the new ID field. I cannot get this to work.

    • April 7, 2010 9:14 am

      Is this what you’re looking for ?

      var jsonData = new {
      total = 1, //todo: calculate
      page = page,
      records = context.Questions.Count(),
      rows = (
      from question in context.Questions
      select new {
      i = question.Id,
      cell = new string[] { question.Id.ToString(), question.Votes.ToString(), question.Title }
      return Json(jsonData);

      Hope it helps !

  12. Twaldron permalink
    April 12, 2010 8:20 pm

    can you help me here? I have done everything I can think of but when i click the row, it doesn’t enter edit mode it just selects the row. To be honest i don’t really understand your idNr and Id, what are the differences between them and how are you constructing that in your json data that you pass.?
    well here is my jqgird if anyone can help it would be great.

    var spainvid = $(“#hiddenspainvid”).val();
    var lastsel;
    var themeURL = ”;
    var gridUr = ”;
    url: gridUr + ‘/’ + spainvid,
    datatype: ‘json’,
    colNames: [‘SpaPartUID’, ‘FieldDesc’, ‘price’],
    colModel: [

    { name: ‘SpaPartUID’, index: ‘SpaPartUID’, width: 100, align: ‘left’, editable: true,edittype:’text’, editoptions: { size: “20”, maxLength: “30”} },
    { name: ‘FieldDesc’, index: ‘FieldDesc’, width: 200, align: ‘left’, editable: true, edittype: ‘text’, editoptions: { size: “20”, maxLength: “30”} },
    { name: ‘price’, index: ‘Price’, width: 200, align: ‘left’, editable: true, edittype: ‘text’, editoptions: { size: “20”, maxLength: “30”} }


    pager: ‘#Accessorypager’,
    rowNum: 10,
    rowList: [5, 10, 20, 50],
    sortname: ‘id’,
    sortorder: “asc”,
    viewrecords: true,
    onSelectRow: function(id) {
    if (id && id !== lastsel) {
    jQuery(‘#Accessorylist’).jqGrid(id, true);
    lastsel = id;
    editurl: ”,
    imgpath: themeURL,
    height: ‘250px’

  13. Bhavin Patel permalink
    May 11, 2010 12:55 pm

    i am trying ur code but and its open the new window for the edit the particular record with the respective values but when i pressed the submit button for edit the record it throws this error-“error Status: Internal Server Error Error code: 500” so how can i solve that error? what mistake i made can you guide me regarding that?
    i need urgent solutions for that.
    can you share your source code with me so i can solve my problem?
    i am working in vs 2010 with MVC2.

  14. Donny permalink
    May 16, 2010 3:42 am

    Hi there, I am just wondering if you can give me some help here. I have a php page set up using jqgrid, I got the add, edit, delete, and search function working, but how can I have the ‘edit’ button onclick function to bring up a custom modal form? I want to try the GridToForm function, but where do I set up the custom form. Should it be coming from another php page, or do I have to build the form within the onclick function? The function needs a ‘formid’, and I really don’t know where I should set up the form? Obviously, it is not going to be in the body of the main form, this is all I know. Any help would be great.

    Thank you

    • May 16, 2010 10:26 am

      I just checked the docs, and it’s indeed a little vague. It says something about hidden forms inside the grid ? I guess the best thing to do is find an example somewhere. I don’t have any experience with this feature of jqgrid.

      Another thing you might want to so is post your question on ? Some very smart people over there, who probably know the answer.

    • Donny permalink
      May 24, 2010 7:58 am

      Thanks for your reply and your tips about the hidden form, I have just figured it out. This is what I did:

      Firstly, I created a hidden form in the body right before where I show the grid, and I have added all the fields to my form with all the field names match with the COLNAMES, so they will auto-populate. And then I added these codes to the section to add an ‘Edit’ button, and then it works right away.
      // userlist is the grid, customerform is the hidden form
      onClickButton : function ()
      var cid=jQuery(“#userlist”).jqGrid(‘getGridParam’,’selrow’);
      $custedit = jQuery(‘#customerform’);
      width: 700,
      position: ‘center’,
      autoOpen: false,
      title:’Edit Customer Record: ‘,

      overlay: {opacity: 0.5, background: ‘black’},


  15. Saurabh permalink
    September 1, 2010 10:32 am

    I have followed your procedure for the inline editing but still I am not able to post the edited grid data to the controller. Can you please throw some light on what could have been wrong?

  16. Ravi permalink
    November 30, 2010 11:32 am


    I have followed all the steps but on editing its not posting back to the controller . Can you please help

    Thanks and regards,

  17. Ravi permalink
    November 30, 2010 11:51 am

    Hi Thanks your code is working .. But i have one prob

    If i press enter then only it will update ..
    If i just change the text and clicked on some other row .. thats is not updating can you please help me ..

    Thanks and regards,

  18. Ravi permalink
    December 1, 2010 8:18 am


    if declare like this the its not firing the Gridsave method
    public ActionResult GridSave(int id,int idnr, string firstName, string lastName)


    public ActionResult GridSave()

    if i declare like this .. its firing the gridsave method that is posting back ..
    can u please tell me how to get the values of the row which are edited
    hanks and regards

  19. Dileep permalink
    September 2, 2011 8:16 am

    As i am beginer in JqGrid and MVC . Please can u suggest me what is exactly the two id’s you are using . Id and id.
    And i have used the same code for my appilcation also but the editURL Action Method is not getting trigger. Please suggest me what is the problem.
    here is my code for JQGrid

    datatype: ‘json’,
    mtype: ‘GET’,
    url: “/AdminThresholdMaintenance/ThresholdMaintenanceResult”,
    height: “auto”,
    pager: true,
    loadui: “disable”,
    colNames: [“Vendor Name”, “Country Name”, “File Type”, “Stage”, “Edit Threshold Level”, “Threshold Level of Suspended Records”],
    colModel: [

    { name: “VendorName”, index: ‘VendorName’, sortable: false },
    { name: “CountryName”, index: ‘CountryName’, sortable: false },
    { name: “FileType”, index: ‘FileType’, sortable: false },
    { name: “Stage”, index: ‘Stage’, sortable: false },
    { name: “EditTrsholdLvl”, index: ‘EditTrsholdLvl’, sortable: false, formatter: details12 },
    { name: “TrshholdLvlofSuspRecs”, index: ‘TrshholdLvlofSuspRecs’, sortable: false,editable:true }
    jsonReader: {
    root: “rows”,
    page: “page”,
    total: “total”,
    records: “records”,
    repeatitems: false
    pager: jQuery(‘#pager’),
    rowNum: 10,
    rowList: [10, 20, 30],
    sortname: ‘VendorName’,
    sortorder: “desc”,
    caption: “Threshold Maintenance”,
    ExpandColumn: “menu”,
    autowidth: false,
    pagerpos: ‘left’,
    onSelectRow: function(id){
    if(id && id!==lastsel){



    editurl: “/AdminThresholdMaintenance/GridSave”


    Action Method in Controller
    public ActionResult GridSave( int id,string VendorName, string CountryName, string FileType, bool EditTrsholdLvl, string TrshholdLvlofSuspRecs)
    public ActionResult GridSave( int id,string VendorName, string CountryName, string FileType, bool EditTrsholdLvl, string TrshholdLvlofSuspRecs)

    return Content(“false”);


    Just i want to trigger the action method after edit

    Thanks and Regards
    Dileep K

    • September 2, 2011 10:12 am

      id is the rowid, jqgrid supplies this when calling your onSelectRow function.

      Mind you this code sample is over 2years old now. You might want to check the current jqGrid wiki for more recent code samples. Also use firebug to debug your javascript code and calls to the server.

  20. Vlad permalink
    September 16, 2011 2:07 pm

    Please, can you show an example, how with the help of callback function get an error on the client?

  21. November 30, 2011 1:33 am

    I have a jqGrid inline editing example at that works much like excel. It allows you to use the tab key to move to the next row, it saves the current row if changes have been made, uses the escape key to abandon editing and uses the enter key to save changes. The grid blur is handled as the escape key. Selecting a row by the row number allows the delete key to delete a row. I think it covers much of what is needed for inline editing. If all looks good the code is free. Let me know if bugs exists.

  22. Leo permalink
    February 6, 2012 11:46 am

    Can you pls explain why my editRow didnot work. I have copied your code
    and it stuck at
    jQuery(‘#list’).editRow(id, true);
    according to, there are 9 params with editRow method. Is it the cause of my failure?
    Please help

    • February 6, 2012 1:38 pm

      My blog post is over 2 years old. Probably things have changed since I posted.


  1. Dew Drop - May 5, 2009 | Alvin Ashcraft's Morning Dew
  2. Sending hidden fields in jqGrid « PaleLocust Labs

Comments are closed.

%d bloggers like this: