1

我正在尝试使用 jqgrid 编辑表单,但我不明白为什么每次选择一行并单击编辑图标时 jqgrid 不调用 asmx web 方法(jqgrid 只是第一次调用 ajax)

这是代码:

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;

}

更新:要解决这个问题,你们必须在 jqGrid 的编辑部分插入“recreateForm:true”

4

1 回答 1

0

您当前的代码中没有'Codice'colModel,但您尝试从该列中获取数据。即使原始服务器响应具有该Codice属性,只有在您添加具有相同名称的附加隐藏列时才会保存该属性。

抱歉,但为了告诉信任,我建议您重写您使用的整个代码。as函数的使用datatype不好。取而代之的是,您可以使用jsonReader. JSON.parse(data.d)have内部$.ajax的调用dataType: "json"表明您在服务器端的 web 方法中犯了一个更重要的错误。它表明您将返回的对象手动转换为,String而不是从 web 方法返回对象。WebService自动将对象转换为 JSON 。由于对 JSON 的手动约定,返回的数据将被两次转换为 JSON。只是因为服务器代码中的错误,您必须使用JSON.parse(data.d)并且不能jsonReader这里描述的那样使用。

于 2012-06-27T08:32:41.680 回答