Pass parameters in Edit Url of jqGrid for Form Editing

10,421

First of all you should decide which editing mode you use. If you want to use form editing then no cellEdit: true option should exist in your code. Yo used wrong option celledit instead of cellEdit, so it will be just ignored, but the existence of such options makes the code more difficult to read. By the way cellsubmit option which you mention in your question (for example cellsubmit: "remote") works only in case of cell editing which required the usage of cellEdit: true.

The code which you posted don't contains any form editing code. It's unclear whether you use navGrid with some options or you formatter: "actions" with formatoptions: {editformbutton: true} or calls editGridRow method directly ... Which options and how exactly you use form editing is unclear from your question so one have to guess what you do.

If you decide to use form editing then you should place editData in correct place. editData is not jqGrid option (see here). It's parameter (option/property) of editGridRow method (see here). Depend on how you use form editing you should place it in the corresponding place. For example if you use navGrid then the 3-d and 4-th parameters of it (see prmEdit and prmAdd) allows you to specify the option forwarded to editGridRow by navGrid if the user click Edit or Add button of the navigator bar. The code which you posted in the question uses correct place for editData, but "adding the editData below the editurl" (see the text of your question) is the wrong way.

You wrote "i have to pass 2 parameters to Controller" (but the code of UpdateData action controller which you posted contains only one parameter gridData). You don't posted colModel which makes more difficult to understand you (by the way you used misunderstanding names: colModel: colname, but colName option have another value colHeader), but probably exactly one column from colModel have editable: true property. In the case the usage of form editing seems me really not the best choice and usage cell editing could be more simple. To use it you need add cellsubmit: "remote", cellEdit: true and cellurl: "/Home/UpdateData". In the case jqGrid will send to the server (to cellurl) 3 parameters (see the documentation):

  • The editing data with the name like the value of name property in colModel.
  • rowid under the name id. One can use prmNames option to change the id name. For example prmNames: {id: "TransactionId"} will change the name of rowid to TransactionId.
  • Fixed string oper=edit. One can change the names by usage prmNames. For example prmNames: {oper: "myOper", editoper: "myEdit"} will change oper=edit to myOper=myEdit.

Additionally one can use beforeSubmitCell and serializeCellData to customize the data:

beforeSubmitCell: function (rowid, name, value, iRow, iCol) {
    return {gridData: gridData};
},
serializeCellData: function (postdata) {
    return JSON.stringify(postdata);
}

You can change serializeCellData in any other way which you need. For example

serializeCellData: function (postdata) {
    return {
        gridData: JSON.stringify(postdata.gridData),
        columnData: JSON.stringify(postdata.columnNameFromColModel)
    };
}
Share:
10,421
A Coder
Author by

A Coder

Code => Game => Sleep => Repeat

Updated on June 04, 2022

Comments

  • A Coder
    A Coder almost 2 years

    I am using jgGrid form editing in which I am updating the edited values. When I click submit the editurl gets called. In that case in my scenario I have to pass two parameters to Controller.

    //jqGrid Code:

        var colname = [];
        var colHeader = [];
        var gridData;
    
    
    var selectedValue;
    var multipleSource;
    var colValues = [];
    var columns = [{ name: 'Workflow Name', width: '200px' }, { name: 'Workflow Category', width: '150px' }, { name: 'Status', width: '100px' }, { name: 'Workflow Owner', width: '150px' }];
    
    $.ajax({
                url: '@Url.Action("LoadColumns","Home")',
               // url: "/Home/LoadColumns",
                data: { 'workflowId': selectedValue, 'status': $('#Status option:selected').val(), 'customView': $('#CustomViews option:selected').val() },
                datatype: 'json',
                type: 'GET',
                success: OnComplete,
                error: OnFail
            });
            function OnComplete(result) {
              //  debugger;
                gridData = $.parseJSON(result)
                colHeader = [];
                colname = [];
                $.each(gridData.Table1, function () {
    
                colHeader.push(this.Name);
    
                switch (this.Datatype) {
    
                    case 'int':
                        colname.push({ name: this.Name, index: this.Name, width: 130, align: 'left', sortable: true, editable: false, sorttype: 'int' });
                        break;
                    case 'String':
                        colname.push({ name: this.Name, index: this.Name, width: 130, align: 'left', sortable: true, editable: true });
                        break;
                    case 'DateTime':
                        colname.push({
                            name: this.Name, search: true, index: this.Name, width: 130, stype: "text", editable: true, searchoptions: {
    
                                dataInit: function (el) {
    
                                    $(el).datepicker({
                                        dateFormat: 'm/d/y', maxDate: 0, changeMonth: true, changeYear: true, onSelect: function (dateText, inst) {
                                            setTimeout(function () {
                                                $('#jQGridDemo')[0].triggerToolbar();
                                            }, 50);
                                        }
                                    });
    
                                }
                            }, editoptions: {
                                dataInit: function (el) {
    
                                    $(el).datepicker({
                                        dateFormat: 'm/d/y', maxDate: 0, changeMonth: true, changeYear: true
                                    });
    
                                }
                            }
                        });
                        break;
                    case 'dropdown':
    
                        colname.push({
    
                            name: this.Name, index: this.Name, width: 130, edittype: "select", formatter: 'select',
                            cellattr: function (rowId, val, rawObject, cm, rdata) {
                                var strVal = [];
                                strVal = val.split("_");
    
                                if (rawObject[cm.name + "_Title"] == "") {
                                  //  debugger;
                                    return 'title="' + strVal[0].toString() + '"';
                                }
                                else
                                    return 'title="' + val + ' (' + rawObject[cm.name + "_Title"] + ')"';
    
                            },
                            editoptions: { value: ':Select;' + this.ValueList.slice(0, -1) }, stype: 'select'
                                    , searchoptions: { value: ':All;' + this.ValueList.slice(0, -1) }, align: 'left', sortable: true, editable: true
                        });
                        break;
                    default:
                        colname.push({ name: this.Name, index: this.Name, width: 130, align: 'left', sortable: true, editable: true });
                        break;
                        break;
                }
    
            });
    
     jQuery("#jQGridDemo").jqGrid({
                data: gridData.BuildTransactionsDataTable,
                datatype: "local",
                hoverrows: false,
                colNames: colHeader,
                colModel: colname,
                id: 'TransactionId',
                localReader: {
                    root: 'rows',
                    id: 'TransactionId',
    
                    repeatitems: false
                },
                rowNum: 10,
                rowList: [10, 20, 30],
                pager: '#jQGridDemoPager',
                sortname: '_id',
                viewrecords: true,
                loadonce: true,
                sortorder: 'desc',
                caption: "Grid",
                gridview: true,
                autoencode: true,
                ignoreCase: true
    
            });
    
    jQuery("#jQGridDemo").jqGrid('filterToolbar', { stringResult: true, searchOperators: true, searchOnEnter: false, defaultSearch: "cn" });
    
    
            $('#jQGridDemo').jqGrid('navGrid', '#jQGridDemoPager',
                       {
                           edit: true,
                           add: true,
                           del: false,
                           search: true,
                           searchtext: "Search",
                           addtext: "Add",
                           edittext: "Edit",
                           deltext: "Delete"
                       },
                        { multipleSearch: true },
                         //{
    
                         {   //EDIT
                             //                       height: 300,
                             //                       width: 400,
                             //                       top: 50,
                             //                       left: 100,
                             //                       dataheight: 280,
                             closeOnEscape: true, //Closes the popup on pressing escape key
                             reloadAfterSubmit: true,
                             drag: true,
    
                             afterSubmit: function (response, postdata) {
                                 debugger;
                                 if (response.responseText == "") {
    
                                     $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
                                     return [true, '']
                                 }
                                 else {
    
                                     $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
                                     return [false, response.responseText]//Captures and displays the response text on th Edit window
                                 }
                             },
    
                             onclickSubmit: function (response, postdata) {
                                 debugger;
                                 var resultGriddata = JSON.stringify(postdata);
                                 var resultColumndata = JSON.stringify(gridData.Table1);
                                 $.ajax({
                                     url: "/Home/UpdateData",
                                     datatype: 'json',
                                     data: { 'gridData': resultGriddata, 'columnData': resultColumndata },
                                     type: 'POST',
                                     success: OnComplete,
                                     error: OnFail
                                 });
                                 function OnComplete(result) {
                                     alert(result);
                                 }
                             },
                             editData: {
                                 TransactionId: function () {
    
                                     var sel_id = $('#jQGridDemo').jqGrid('getGridParam', 'selrow');
                                     var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id');
                                     return value;
    
                                 }
                             }
    
    
                         },
                   {
                       closeAfterAdd: true, //Closes the add window after add
                       afterSubmit: function (response, postdata) {
                           debugger;
                           if (response.responseText == "") {
    
                               $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
                               return [true, '']
                           }
                           else {
                               alert(response);
                               $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
                               return [false, response.responseText]
                           }
                       }
                   },
                   {   //DELETE
                       closeOnEscape: true,
                       closeAfterDelete: true,
                       reloadAfterSubmit: true,
                       closeOnEscape: true,
                       drag: true,
                       afterSubmit: function (response, postdata) {
                           if (response.responseText == "") {
    
                               $("#jQGridDemo").trigger("reloadGrid", [{ current: true }]);
                               return [false, response.responseText]
                           }
                           else {
                               $(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
                               return [true, response.responseText]
                           }
                       },
                       delData: {
                           TransactionId: function () {
                               var sel_id = $('#jQGridDemo').jqGrid('getGridParam', 'selrow');
                               var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id');
                               return value;
                           }
                       }
                   },
                   {//SEARCH
                       closeOnEscape: true
    
                   }
            );
      }
    

    In this code I have passed three parameters which makes the grid loaded:

    //Controller Code:

     [HttpPost]
            public ActionResult UpdateData(string gridData, string columnData)
            {
    
                return Content("Success");
    
            }
    

    I have tried it in two ways:

    1. Adding EditData: I have tried adding the editData below the editurl and tried passing a single parameter. But i got null as a result in the Controller.

     editData: { _dokdata: function () { return JSON.stringify(gridData); } }
    

    2. Passing data in onclickSubmit: I have tried posting the data to controller in the onclickSubmit event. Like,

     onclickSubmit: function (response, postdata) {
    
                                 postdata.extraParam = gridData;
                                 var resultGriddata = JSON.stringify(postdata);
                                 var resultColumndata = JSON.stringify(gridData.Table1);
                                 $.ajax({
                                     url: "/Home/UpdateData",
                                     datatype: 'json',
                                     data: { 'gridData': resultGriddata,     'columnData':resultColumndata },
                                     type: 'POST',
                                     success: OnComplete,
                                     error: OnFail
                                 });
                                 function OnComplete(result) {
                                     alert(result);
                                 }
                             },
    

    Now in the onclickSubmit I have to pass both parameters and get those values into the controller. Right now the controller is getting called with both parameters with values as expected(the data). I am not sure of the other events in the code.

    But after the process in code behind I get error in the edit popup saying that "Url is not set". So I tried in many ways giving like 'clientarray' for editurl and cellsubmit, but nothing helped.

    It was said that in my search, all should be given for InlineEdit and not for FormEdit. Not sure i'm where i'm wrong.

    How can I make this work without showing the error in the popup?

    SampleData:

    {"Table1":[{"Name":"Have Queries","Datatype":"String","ValueList":"","ValueId":"139646","ValueType":"F"},{"Name":"Assign to Karthik","Datatype":"String","ValueList":"","ValueId":"139665","ValueType":"F"},{"Name":"Field Format","Datatype":"DateTime","ValueList":"","ValueId":"141803","ValueType":"F"},{"Name":"URLFields","Datatype":"String","ValueList":"","ValueId":"447592","ValueType":"F"},{"Name":"Testing","Datatype":"String","ValueList":"","ValueId":"705958","ValueType":"F"},{"Name":"Start Task","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139584","ValueType":"T"},{"Name":"Create Credentials","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139585","ValueType":"T"},{"Name":"Branching and Mapping","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139586","ValueType":"T"},{"Name":"Application Walkthrough","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139587","ValueType":"T"},{"Name":"Call","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139588","ValueType":"T"},{"Name":"Queries","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139589","ValueType":"T"},{"Name":"Development Ready","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139591","ValueType":"T"},{"Name":"Assign","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139666","ValueType":"T"},{"Name":"Check Developer","Datatype":"dropdown","ValueList":"In Process:In Process;Completed:Completed;Re-Work Required:Re-Work Required;Assigned:Assigned;Not Required:Not Required;","ValueId":"139701","ValueType":"T"}],"Table2":[{"TransactionId":"141090","TransactionStatus":"29607","StartDate":"1/18/1900 5:02:00 PM","Have Queries":"Y","Assign to Karthik":"Yes","Field Format":"","URLFields":"","Testing":"","Start Task":"Completed","Start Task_Title":"43_False","Create Credentials":"Completed","Create Credentials_Title":"_False","Branching and Mapping":"Completed","Branching and Mapping_Title":"2_False","Application Walkthrough":null,"Application Walkthrough_Title":null,"Call":"Completed","Call_Title":"_False","Queries":null,"Queries_Title":null,"Development Ready":null,"Development Ready_Title":null,"Assign":null,"Assign_Title":null,"Check Developer":null,"Check Developer_Title":null},{"TransactionId":"141101","TransactionStatus":"29607","StartDate":"5/10/2013 12:00:00 AM","Have Queries":"N","Assign to Karthik":"Yes","Field Format":"","URLFields":"","Testing":"","Start Task":"Completed","Start Task_Title":"43_False","Create Credentials":"In Process","Create Credentials_Title":"2_True","Branching and Mapping":"Completed","Branching and Mapping_Title":"_False","Application Walkthrough":"Completed","Application Walkthrough_Title":"_False","Call":"Completed","Call_Title":"_False","Queries":null,"Queries_Title":null,"Development Ready":null,"Development Ready_Title":null,"Assign":null,"Assign_Title":null,"Check Developer":null,"Check Developer_Title":null}]}
    
  • A Coder
    A Coder over 9 years
    Since this grid is to be viewed in mobile and to make the edit more visualize i need to use form editing. Its showing me "Url is not set" but i'm able to receive the values in code behind. In the UI it shows me the error. Why?
  • Oleg
    Oleg over 9 years
    @SanthoshKumar: You should post the code which corresponds form editing. As I worte in my answer: 1) The code which you posted have no line which corresponds form editing. 2) You should include the code which shows exactly where you placed editData, onclickSubmit etc. and the definition of colModel (at least columnData column).
  • A Coder
    A Coder over 9 years
    Updated the question. Kindly help.
  • Oleg
    Oleg over 9 years
    @SanthoshKumar: The code still don't contains colModel which is important (see my previous comment). It's not good to use .trigger('reloadGrid') inside of afterSubmit. The call of $.ajax should be also removed from onclickSubmit. The current code have no editurl: "/Home/UpdateData". UpdateData contains no id so you will have no information which row will be edited. If you want to send _id (TransactionId) as the parameter of UpdateData then you should verify how you fill the data in the grid. If you fill the data correctly then rowid (send as id) contains it.
  • A Coder
    A Coder over 9 years
    Added now. Let me know anything is needed.
  • A Coder
    A Coder over 9 years
    Also updated the question. But haven't changed anything in the code. Just i need to get rid of the error thrown in the popup and get the values updated.
  • Oleg
    Oleg over 9 years
    How you fill the data in the grid? If you fill the data correctly then rowid (send as id) contains it. Could you include test data with 2 rows? Have the data _id or TransactionId property or both? By the way it's very bad to use name of colModel which have special meta-characters like spaces.
  • A Coder
    A Coder over 9 years
    Its a very big process in the code behind and its complicated to reproduce.
  • Oleg
    Oleg over 9 years
    What to reproduce? I asked you to include test data with 2 rows. For example [{"_id":123, "TransactionId":986, "Workflow Name": "wn1", "Workflow Category": "wc1", "Status": "OK", "Workflow Owner": "o1"}, {"_id":456, "TransactionId":765, "Workflow Name": "wn2", "Workflow Category": "wc2", "Status": "Failed", "Workflow Owner": "o2"}]. Corresponds it to your data or some properties? The first error in your code: it have no editurl option. Other error you use var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id'); and sortname: '_id', but colModel have no name: "_id" column.
  • Oleg
    Oleg over 9 years
    @SanthoshKumar: The next error: no column (see columns which you included) contains editable: true property. The next error you should don't define colModel with name having spaces or any meta-characters such as !"#$%&'()*+,./:;<=>?@[\]^{|}~` (you use name: 'Workflow Name' for example) because 1) name value will be used to build id values which should not have the characters. 2) the names of parameters of UpdateData should be the same as name value of editable columns. Try to declare in C# variable with the name Workflow Name (with spaces) or class with the property.
  • A Coder
    A Coder over 9 years
    Have added the sample data in question. I have added edit url first but thought of using the onclickSubmit i removed that. Not sure how to modify the code to make it work.
  • A Coder
    A Coder over 9 years
    I could able to receive the desired data in the controller. Not sure why i'm getting the "Url not set" error in the popup after executing the submit functionality.