jqGrid的编辑AJAX调用每一次 [英] jqgrid edit call ajax every time

查看:318
本文介绍了jqGrid的编辑AJAX调用每一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jqGrid的编辑形式,但我不明白为什么jqGrid的不叫ASMX Web方法每次我选择行时间,我点击编辑按钮(调用的jqGrid AJAX只是第一次)

I'm trying to use jqgrid edit form, but I can't understand why jqgrid do not call asmx web method every time I select a row and I click on edit icon (jqgrid call ajax just the first time)

这是code:

function Grid() {  
   var ret = Array();

   var grid = jQuery("#grid");


var hideLoading = function () {
    $("#lui_" + grid).hide();
    $("#load_" + grid).hide();
}

var strSearch = "";
var strField = "";
var strOper = "";

//
//  handler: si occupa di creare il contenuto del menu a tendina (form jqGrid)
//
var buildOptions = function (dataList) {
    var response = dataList;
    var option = "";

    if (response && response.length) {
        for (var i = 0, l = response.length; i < l; i++) {

        if (response[i]["selectedvalue"] == "on")
            option += '<option role="option" selected="selected" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
        else
            option += '<option role="option" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
        }
    }

    return option;
};

grid.jqGrid({
    // setup custom parameter names to pass to server
    prmNames: {
        search: "isSearch",
        nd: null,
        rows: "numRows",
        page: "page",
        sort: "sortField",
        order: "sortOrder"
    },
    // add by default to avoid webmethod parameter conflicts
    postData: {
        searchString: '',
        searchField: '',
        searchOper: ''
    },
    // setup ajax call to webmethod
    datatype: function (postdata) {
        $.ajax({
        url: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateDiscount") %>',
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(postdata),
        dataType: "json",
        success: function (data, st) {
            if (data.d == "KO") {
            grid.GridUnload();

            jAlert("La ricerca non ha restituito alcun risultato", "Book2Guest");

            return false;
            }

            if (st == "success") {
            var grid = $("#grid")[0];
            grid.addJSONData(JSON.parse(data.d));
            ret = JSON.parse(data.d);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            jAlert("Si è verificato un errore: " + textStatus + " " + errorThrown + " -- " + $.parseJSON(xhr.statusText), "Book2Guest");
        }
        });
    },
    // this is what jqGrid is looking for in json callback
    jsonReader: {
        root: "rows",
        page: "page",
        total: "totalpages",
        records: "totalrecords",
        cell: "cell",
        id: "id",
        userdata: "userdata",
        repeatitems: true
    },
    ajaxSelectOptions: {
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        data: {
            rowId: function () {
                if (JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']) == undefined)
                    return "";

                return JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']);
            }
        }
    },
    colNames: ['ID', 'Rate'],
    colModel: [
        { name: 'ID', index: 'ID', width: 10, align: "center", search: false, sorttype: 'int', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
        {
        name: 'TariffaCodiceOfferta',
        index: 'TariffaCodiceOfferta',
        width: 50,
        hidden: true,
        formatter: 'select',
        editable: true,
        edittype: 'select',
        editrules: { edithidden: true }, //, required: true },
        editoptions: {
            multiselect: true,
            dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateListByRowId") %>',
            buildSelect: function (data) {
                var response = $.parseJSON(data.d);

                var option = buildOptions(response);
                var s = '<select>';
                s += option;

                return s + "</select>";
            },
            dataInit: function (elem) {
                setTimeout(function () {
                    $(elem).multiselect({ selectedList: 10 });
                }, 50);
            },
            multiple: true
        }
        },
      ],
rowNum: 10,
rowList: [10, 20, 30],
height: 'auto',
pager: '#gridpager',
viewrecords: true,
shrinkToFit: false,
loadComplete: function () {
    hideLoading();
},
loadError: function () {
    hideLoading();
},
editurl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/SaveRoomDiscount") %>',
sortname: "ID",
sortorder: "asc",
caption: "Rate list",
onSelectRow: function (id, status) {},
ondblClickRow: function (rowid) {
    grid.jqGrid('editGridRow', rowid,
    {
    width: 450,
    height: 450,
    closeOnEscape: true,
    addCaption: "Add Rate",
    editCaption: "Edit Rate",
    bSubmit: "Salva",
    bCancel: "Annulla",
    bClose: "Chiudi",
    bYes: "Si",
    bNo: "No",
    bExit: "Annulla",
    editData: { 
        "codice": function () {
            var selectedRow = grid.getGridParam("selrow");
            var rowData = grid.getRowData(selectedRow);
            return rowData["Codice"];
        }
    },
    viewPagerButtons: false,
    closeAfterEdit: true,
    reloadAfterSubmit: true,
    beforeShowForm: function (form) {
        var dlgDiv = $("#editmod" + grid[0].id);
        var parentDiv = dlgDiv.parent(); // div#gbox_list
        var dlgWidth = dlgDiv.width();
        var parentWidth = parentDiv.width();
        var dlgHeight = dlgDiv.height();
        var parentHeight = parentDiv.height();

        // Grabbed jQuery for grabbing offsets from here:
        //http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
        var parentTop = parentDiv.offset().top;
        var parentLeft = parentDiv.offset().left;

        dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
        dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
    },
    onClose: function (response, postdata) {
    }
    });

    return;
},
gridComplete: function () {
    if (grid.getGridParam('records') == 0) // are there any records?
    DisplayEmptyText(true);
    else
    DisplayEmptyText(false);
},
emptyDataText: 'There are no records. '
})
grid.setGridWidth(900, true);
grid.jqGrid('navGrid', '#gridpager',
{
    edit: true,
    view: false,
    add: false,
    del: true,
    search: false
},
//prmEdit
{
    width: 450,
    height: 300,
    closeOnEscape: true,
    addCaption: "Aggiungi Offerta",
    editCaption: "Modifica Offerta",
    bSubmit: "Salva",
    bCancel: "Annulla",
    bClose: "Chiudi",
    saveData: "Sono state apportate delle modifiche, sei sicuro di voler continuare?",
    bYes: "Si",
    bNo: "No",
    bExit: "Annulla",
    editData: { 
        "Codice": function () {
            var selectedRow = grid.getGridParam("selrow");
            var rowData = grid.getRowData(selectedRow);
            return rowData["Codice"];
        } 
    },
    viewPagerButtons: false,
    closeAfterEdit: true,
    reloadAfterSubmit: true,
    beforeShowForm: function (form) {
        var dlgDiv = $("#editmod" + grid[0].id);
        var parentDiv = dlgDiv.parent(); // div#gbox_list
        var dlgWidth = dlgDiv.width();
        var parentWidth = parentDiv.width();
        var dlgHeight = dlgDiv.height();
        var parentHeight = parentDiv.height();

        // Grabbed jQuery for grabbing offsets from here:
        //http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
        var parentTop = parentDiv.offset().top;
        var parentLeft = parentDiv.offset().left;

        dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
        dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
    },
    onClose: function (response, postdata) {}
}
//prmSearch, 
//prmView
);
return ret;

}

更新:要解决这个问题,你们有插入'recreateForm:真正的'中的jqGrid的编辑部分

UPDATE: to solve this issue, you guys have to insert 'recreateForm: true' in the edit section of jqGrid

推荐答案

您当前code没有Codice colModel ,但你尝试从列获取数据。即使原始服务器响应有 Codice 属性,该属性将仅当您使用相同的名称添加额外的隐藏的列保存。

You current code don't have 'Codice' column in colModel, but you try to get the data from the column. Even if the original server response has the Codice property, the property will be saved only if you add additional hidden column with the same name.

很抱歉,但告诉我建议你重写你使用整个code的信任。 数据类型作为功能的使用是不好的。相反的,你可以使用 jsonReader 。该调用 JSON.parse(data.d) $内阿贾克斯数据类型: JSON显示您在服务器端将WebMethod做了一件更重要的错误。这表明你做返回的对象手动转换为字符串而不是从Web方法返回的对象的。转换的WebService对象以JSON的自动由于手动公约为JSON返回的数据将是的两次的转换成JSON。只是由于在服务器code,你必须使用错误的 JSON.parse(data.d),并不能只用 jsonReader 描述的一样这里例如

Sorry, but to tell the trust I would recommend you to rewrite the whole code which you use. The usage of datatype as function is not good. Instead of that you can use jsonReader. The call JSON.parse(data.d) inside of $.ajax having dataType: "json" shows that you did one more important error in the webmethod on the server side. It shows that you make manual conversion of returned object to String instead of returning object from the web method. WebService convert the object to JSON automatically. Because of manual convention to JSON the returned data will be twice converted to JSON. Only because of the error in the server code you have to use JSON.parse(data.d) and can't just use jsonReader like described here for example.

这篇关于jqGrid的编辑AJAX调用每一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆