Pass updated value from jqGrid popup to Controller

2019-03-01 13:07发布

问题:

I have a jqgrid in which during edit of a row the popup gets opened and after updating the values it has to be sent to the controller. Now the method in the controller is called but i'm not sure how to pass the values to the controller.

//jqGrid:

jQuery("#jQGridDemo").jqGrid({
    url: '@(Url.Action("LoadData", "Home"))',
    datatype: "json",
    mtype: 'GET',
    colNames: ['ProductId', 'Name', 'AdminContent', 'ProductTemplate', 'CreatedOnUtc'],
    colModel: [{ name: 'ProductId', index: 'ProductId', width: 200, align: 'left', sorttype: 'int' },
                    { name: 'Name', index: 'Name', width: 200, align: 'left', sortable: true, editable: true },
                    { name: 'AdminContent', index: 'AdminContent', width: 200, align: 'left', sortable: true, editable: true },
                    { name: 'ProductTemplate', index: 'ProductTemplate', width: 200, editable: true, edittype: "select", editoptions: { value: "1:VariantsInGrid;2:SingleProductVariant;3:MultipleProducts" }, align: 'left' },
                    { name: 'CreatedOnUtc', index: 'CreatedOnUtc', width: 200, align: 'left', edittype: 'text', formatter: 'date', formatoptions: { newformat: 'm-d-Y' }, datefmt: 'm-d-Y',
                        editoptions: {
                            size: 10, maxlengh: 10,
                            dataInit: function (element) {
                                $(element).datepicker({ dateFormat: 'yy.mm.dd' })
                            }
                        }, sortable: true, editable: true
                    }
        ],

                    jsonReader: {
                        root: 'rows',
                        total: 'total',
                        page: 'page',
                        records: 'records',
                        cell: 'cell',
                        id: 'id',
                        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,
    editurl: '@(Url.Action("EditData", "Home"))'

});


jQuery("#jQGridDemo").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });

$('#jQGridDemo').jqGrid('navGrid', '#jQGridDemoPager',
               {
                   edit: true,
                   add: true,
                   del: true,
                   search: true,
                   searchtext: "Search",
                   addtext: "Add",
                   edittext: "Edit",
                   deltext: "Delete"
               },
               {   //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
                       }
                   },
                   editData: {
                       EmpId: 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) {

                       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: {
                       EmpId: function () {
                           var sel_id = $('#jQGridDemo').jqGrid('getGridParam', 'selrow');
                           var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id');
                           return value;
                       }
                   }
               },
               {//SEARCH
                   closeOnEscape: true

               }
        );

//Controller:

 [HttpPost]
        public ActionResult EditData()
        {

            return View();
        }

I have some three rows in the pop which is been updated. Now all those values along with the id has to be sent to the controller.

Any help?

回答1:

It's important to understand that jqGrid always assign id attribute to every row (<tr> element) of the grid which one names "rowid" in the documentation. If you have some native unique value which can be interpreted as the rowid, like ProductId then you should include key: true property to the definition of ProductId column in colModel. Alternatively you can use jsonReader: {id: "ProductId"}. In the case the property ProductId of every item will be used as rowid. If you use jsonReader: {id: "ProductId"} option you don't really need to include the column ProductId in colModel.

If you fill the grid correctly then jqGrid will send rowid as id parameter to the EditData controller together with all other editable columns. You can use prmNames: {id: "ProductId"} to rename id parameter to ProductId. In the case you can declare EditData just as

public ActionResult EditData(Product product)

The usage of return View(); inside of EditData will be wrong. You should return empty data typically. You need to use $(this).jqGrid('setGridParam', { datatype: 'json' }) only without trigger('reloadGrid') because jqGrid reload the grid after editing per default (reloadAfterSubmit: true is default value).

UPDATED: One more remark. jqGrid use HTTP status code to detect whether loading of grid or editing is wrong or not. So the part of afterSubmit where you use return [false, response.responseText] will probably never work. On the other side I would recommend you to use loadError callback in every grid. See the answer or details. Additionally you can consider to return JSON data from the controller in case of errors too. See HandleJsonExceptionAttribute definition and usage of [HandleJsonException] in the old answer. To process JSON error in case of editing you will need to use errorTextFormat callback of form editing.