JQGrid如何在添加新记录之前预填充

时间:2013-03-06 12:07:25

标签: jqgrid insert

我正在向jqgrid添加新数据。数据与客户相关,因此新记录必须包含客户ID。因此,我想要添加记录的弹出窗体应该预先填充客户代码(readonly)。客户代码可在下拉列表中找到。 我尝试了以下内容 - 添加了一个带有自定义函数AddRow的自定义按钮(这是来自Internet的借来的代码)。在函数内部,我使用setColProp将CustomerId设置为字段。然而,没有发生。甚至没有出现弹出窗口。 有没有更简单的方法做同样的事情?

        jQuery("#list").jqGrid({
                url: '<%= ResolveClientUrl("~/service/OfficeData.asmx/GetDealer_SMS") %>',
                editurl: '<%= ResolveClientUrl("~/service/OfficeData.asmx/InsertDealer_SMS") %>',
                datatype: "json",
                mtype: 'POST',
                ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
                ajaxEditOptions: { ContentType: 'application/json; charset=utf-8', dataType: 'json' },
                serializeGridData: function (postData) {
                    //alert("Call");
                    if (postData.DealerCode === undefined) { postData.DealerCode = DealerCode; }
                    else {
                        postData.DealerCode = DealerCode;
                    }
                    return JSON.stringify(postData);
                },
                jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
                colNames: ['ID', 'DealerCode', 'Name', 'Designation', 'Address', 'EMail', 'Mobile'],
                colModel: [{ name: 'id', index: 'id', width: 10, align: 'left', editable: true, hidden: true,
                    editrules: { required: false },
                    editoptions: {
                        dataInit: function (element) {
                            $(element).attr("readonly", "readonly");
                        }
                    }
                },
                { name: 'DealerCode', index: 'DealerCode', width: 60, align: 'left', editable: true,
                    editrules: { required: true },
                    editoptions: {
                        dataInit: function (element) {
                            $(element).attr("readonly", "readonly");
                        }
                    }
                },
                { name: 'RecpName', index: 'RecpName', width: 150, align: 'left', editable: true,
                    editrules: { required: true }, editoptions: { size: 30, maxlength: 150 }
                },
                { name: 'RecpDesignation', index: 'RecpDesignation', width: 100, align: 'left', editable: true,
                    editrules: { required: true }, editoptions: { size: 30, maxlength: 150 }
                },
                { name: 'RecpAddress', index: 'RecpAddress', width: 250, align: 'left', editable: true,
                    editrules: { required: true }, editoptions: { size: 30, maxlength: 400 }
                },
                { name: 'RecpEMail', index: 'RecpEMail', width: 150, align: 'left', editable: true,
                    editrules: { required: true }, editoptions: { size: 30, maxlength: 150 }
                },
                { name: 'RecpMobile', index: 'RecpMobile', width: 100, align: 'left', editable: true,
                    editrules: { required: true }, editoptions: { size: 30, maxlength: 30 }
                }],
                loadError: function (jqXHR, textStatus, errorThrown) {
                    alert('Error while loading -' + errorThrown);
                },
                pager: jQuery('#pager'),
                rowNum: 20,
                rowList: [10, 20, 50],
                sortname: 'RecpName',
                sortorder: "asc",
                viewrecords: true,
                imgpath: '/scripts/themes/steel/images',
                caption: 'Dealer Recepient Details'
            }).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false })

            .navButtonAdd('#pager',
    { caption: "Add",
    buttonicon: "ui-icon-plus",
 onClickButton: addRow,

  title: "",
  cursor: "pointer"
 }
 )
      .navButtonAdd('#pager',
        { caption: "Edit",
      buttonicon: "ui-icon-pencil",
     onClickButton: editRow,
     position: "last",
    title: "",
    cursor: "pointer"
    }
   ).navButtonAdd('#pager',
   { caption: "Delete",
   buttonicon: "ui-icon-trash",
   onClickButton: deleteRow,
   position: "last",
   title: "",
   cursor: "pointer"
  }
  );


            function addRow() {
                alert(DealerCode);
                $("#grid").jqGrid('setColProp', 'DealerCode', { editoptions: { readonly: true, size: 10, value: DealerCode} });


                $('#grid').jqGrid('editGridRow','new',
{ url: '<%= ResolveClientUrl("~/service/OfficeData.asmx/InsertDealer_SMS") %>',
editData: {},
serializeEditData: function(data){
data.id = 0;
return $.param(data);
},
recreateForm: true,
beforeShowForm: function(form) {
$('#pData').hide();
$('#nData').hide();

},
beforeInitData: function(form) {},
closeAfterAdd: true,
reloadAfterSubmit:true,
afterSubmit : function(response, postdata)
{
var result = eval('(' + response.responseText + ')');
var errors = "";
if (result.success == false) {
for (var i = 0; i < result.message.length; i++) {
errors += result.message[i] + "<br/>";
}
} else {
$('#msgbox').text('Entry has been added successfully');
$('#msgbox').dialog(
{ title: 'Success',
    modal: true,
buttons: {"Ok": function() {
$(this).dialog("close");}
}
});
}
// only used for adding new records
var newId = null;
return [result.success, errors, newId];
}
});


} // end of addRow

提前致谢

2 个答案:

答案 0 :(得分:0)

我就是这样做的:

 jQuery("#subgridTable")
                .navButtonAdd('#pager',{
                    caption:"", 
                    title:"Add Row", 
                    buttonicon:"ui-icon-plus", 
                    onClickButton: function(){ 

// The next line loads the form I will use to add information to the table into a div called subgrid_popup_form_container

                        dialog = $("#subgrid_popup_form_container").load(ROOT + "/admin/contact/edit.do?id=0&sid=${station_id}");

// Then I use the dialog function from JQuery UI to get the form(div) into a modal dialog.
                        dialog.dialog({
                            modal:true,
                            height: minHeight,
                            width: minWidth,
                            zIndex: 2000,
                            title: 'Novo Contato',
                            close: function(event, ui) {dialog.empty()},
                        }); 
                    }, 
                    position:"last"
                })

表单提交按钮中,我将信息添加到数据库中(您可以将其添加到您的数组或其他任何内容),然后在最后我调用jQuery("#grid").trigger("reloadGrid");来刷新网格全新的数据。

在您的情况下,您可以创建HTML表单并使其为您填充ID,然后当您保存数据并刷新网格时,您的新行将在那里。

答案 1 :(得分:0)

可以解决它---

  }).jqGrid('navGrid', '#pager', { edit: true, add: true, del: true, refresh: true, search: true },
        {
            ajaxEditOptions: { contentType: 'application/json; charset=utf-8', dataType: 'json' },
            serializeEditData: function (postData) {
                return JSON.stringify(postData);
            },
            closeAfterEdit: false
        },
        {
            beforeInitData: function (formid) {
                $("#list").jqGrid('setColProp', 'DealerCode', { editoptions: { value:         
         DealerCode, readonly: 'readonly'} });
            },
            afterShowForm: function (formid) {
                $("#list").jqGrid('setColProp', 'DealerCode', { editable: false });
            },
            afterSubmit: function (response) {
                var myInfo = '<div class="ui-state-highlight ui-corner-all">' +
             '<span class="ui-icon ui-icon-info" ' +
                 'style="float: left; margin-right: .3em;"></span>' +
             response.responseText +
             '</div>',
    $infoTr = $("#TblGrid_" + $.jgrid.jqID(this.id) + ">tbody>tr.tinfo"),
    $infoTd = $infoTr.children("td.topinfo");
                $infoTd.html(myInfo);
                $infoTr.show();

                // display status message to 3 sec only
                setTimeout(function () {
                    $infoTr.slideUp("slow");
                }, 3000);

                return [true, "", ""]; // response should be interpreted as successful
            },