Reloading data and afterSubmit, aftersavefunc functions not working in jqGrid using MVC on inline RowAdd or RowSave

StackOverflow https://stackoverflow.com/questions/14246280

سؤال

I'm using jqGrid and doing inline editing and row adding. I'm setting everything up on the client side using Javascript and MVC using C# for the server side code. Everything seems to work fine, except when the inline save and add row functions return from the server. If the save fails or errors out, the client seems to remain unaware of the response. I set up some basic functions to handle the afterSubmit, afterSave, etc., but the only instance when it works is on the refresh action. Whenever I edit or add a row, the response does not seem to come back and the grid is not refreshed.

Everything I have found on this has been the basic set-up of the grid to handle this, but I'm afraid that I may not be returning a proper response or some of my functions are set up incorrectly. I have read the wiki documentation and several posts in the forums here and over at Trirand, but there are gaps in the information that leave me with the same issues.

Just to be clear the editing and adding works fine, as does manual refresh, etc. The only issue is returning a response from the server and reloading the data in the grid after the editing is done.

This is my client code relevant to the grid and functions:

My AfterFunctions:

var actionAfterSubmit = function (response, postdata) {
    var res = response.responseText;
    alert('In actionAfterSubmit');
    return [true, ''];
};

var actionbeforeSubmit = function (response, postdata) {
    //var res = response.responseText;
    alert('In beforeSubmit');
    return true;
};

var actionAfterSave = function (rowid, response) {
    alert('In actionAfterSave');
};

var actionErrorFunc = function (rowid, response) {
    alert('In actionErrorFunc');
};

var actionSuccessFunc = function (response) {
    alert('In actionSuccessFunc');
    return true;

};      

My Grid:

jQuery("#list").jqGrid({
        url: ServiceURL + '/Controller/GetDataAction', //URL that loads data including search functionality
        datatype: 'json',
        mtype: 'GET',
        postData: { tableName: t_Name },
        editData: { tableName: t_Name },
        colModel: col_model, //col_model is passed as parameter
        pager: jQuery('#pager'), //sets pager name
        rowNum: 20, //default number of rows
        rowList: [10, 20, 50, 100], //number of row options
        sortname: 'id', //sorting columns
        sortorder: "asc", //sorting order
        viewrecords: true,
        altRows: true, //enables different styling for alternate rows
        altclass: 'myAltRowClass', //Alternate row styling
        width: "100%",
        height: "100%",
        caption: '',
        navigator: true, //enables navigator toolbar
        multipleSearch: true, //enables multiple search features
        multipleGroup: true, //enables grouping in multiple search
        editurl: ServiceURL + '/Controller/GridSaveAction' //URL that handles edit (insert & update) }); var editOptions = {
        width: 400,
        height: 'auto',
        addCaption: "Add Record",
        editCaption: "Edit Record",
        bSubmit: "Submit",
        bCancel: "Cancel",
        bClose: "Close",
        saveData: "Data has been changed!",
        bYes: "Yes",
        bNo: "No",
        bExit: "Cancel",
        recreateForm: true,
        url: ServiceURL + '/ICMP/MapTable/GridSave/',
        reloadAfterSubmit: true,
        closeOnEscape: true,
        closeAfterEdit: true,
        viewPagerButtons: false,
        afterSubmit: actionAfterSubmit,
        afetrsavefunc: actionAfterSave,
        reloadAfterSubmit: true,
        datatype: 'json'

    };

My Parameters and other grid setups:

var addOptions = {
        afterSubmit: actionAfterSubmit,
        aftersavefunc: actionAfterSave,
        errorfunc: actionErrorFunc,
        successfunc: actionSuccessFunc,
        afterComplete: refreshTableAfterAddOrEdit,
        reloadAfterSubmit: true

    };  

var addParameters = {
        useFormatter: true,
        defaultValue: "",
        useDefValues: true,
        initdata: { tableName: t_Name },
        addRowParams: editOptions,
        reloadAfterSubmit: true  };      

var inlineParameters = {
        edit: false,
        editicon: "ui-icon-pencil",
        save: false,
        saveicon: "ui-icon-disk",
        cancel: false,
        cancelicon: "ui-icon-cancel",
        add: true,
        addicon: "ui-icon-plus",
        addParams: addParameters,
        editParams: editOptions,
        reloadAfterSubmit: true,
        restoreAfterSelect: false            
    };


jQuery("#list").jqGrid('navGrid', '#pager', { view: true, edit: true, add: false, del: false, refresh: true, search: true }, editOptions, addParameters, {}, searchOptions, viewOptions);

jQuery("#list").jqGrid('inlineNav', '#pager', inlineParameters);

jQuery("#list").jqGrid('filterToolbar', {
        stringResult: true, searchOnEnter: false, defaultSearch: "cn",
        beforeSearch: function() {
            $("#list").setGridParam({ postData: { _search: true, tableName: t_Name } });
        }    
    });

jQuery("#list").jqGrid('addRow', {
        useFormatter: true,
        useDefValues: true,
        initdata: { tableName: t_Name },
        addRowParams: addParameters
    });

This is my Controller

public JsonResult GridSaveAction(string id, jqGridMapTableModel MapRecord, string tableName, FormCollection formCollection, string someVal)
    {
        //Does some things
        try
        {                
          //Sets up update 
          success = DataAccessObject.Update(Query, myParameters); //Runs the update and returns true if success or false if it failed

        }
        catch (Exception ex) {
             return Json(ex.Message);    
        } 
        return Json(success ? "Operation succesful." : "Operation failed.");
    }

I have been trying everything I can find, but nothing works, and I'm thinking some part of my code is wrong.

Any help is greatly appreciated!

هل كانت مفيدة؟

المحلول

Finally figured out the missing piece of the puzzle!! When using inline editing and the Action buttons column, the onSuccesss, onError and afterSave functions MUST be hard coded into the column model for the grid.

In my case I was using the "Actions" column in the grid to house the edit functionality with a button. This is the button with the pencil icon that enables the inline edit.

This column uses the formatter = "actions" and has its EditActionIconsColumn = true. I had to define the

formatoptions ={
afterSave: function (rowid) { $("#grid").trigger("reloadGrid"); }, 
...
}

all of this is defined in the column model for my "Actions" column only.

The jQGrid script uses only these methods when doing the inline editing through these buttons and ignores any other places where you may have set up this functionality.

That's it. No other complicated code, no manual coding of the inline save functionality. Any other code may be implemented here as well as any of the other functionality like onError or onSuccess.

نصائح أخرى

As you are handling the exception returning a Json message, your "actionErrorFunc" is not being called. Try to throw the Exception and see if will fire the function.

Here's a sample:

private ActionResult ReturnJson(String msg)
{
    Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
    return Content(msg, MediaTypeNames.Text.Plain);
}

public ActionResult Delete(Int32 id)
{
    string success = "ok";
    try
    {
        //code to delete         
    }
    catch (Exception ex)
    {
        return ReturnJson(ex.Message);
    }
    return Json(success);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top