我正试图通过调用ajax web方法(asp.net)在表单编辑jqgrid中构建一个select元素。
如果我调用一个没有参数的方法,一切都会很好。如果我试图调用一个需要字符串参数的Web方法,它就不起作用:
这是代码的摘录:
ajaxSelectOptions: { type: "POST", contentType: 'application/json; charset=utf-8', },
colNames: ['City', 'State'],
colModel: [
{
name: 'City',
index: 'City',
align: "center",
width: 80,
searchoptions: { sopt: ['eq', 'ne', 'cn']} ,
edittype: 'select',
editable: true,
editrules: { required: true },
editoptions: {
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceGeographic.asmx/GetCityByState") %>',
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
var s = '<select id="customer_City" name="customer_City">';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
s += '<option value="' + response[i]["Id"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return s + "</select>";
}
}
},
...
在哪里可以设置要发送到GetCityByState Web方法的参数?
EDIT:我没有强调我正在使用POST调用webmethod。即使我按照Oleg在这个链接上的建议进行了尝试,它也不起作用:(
我认为您需要jqGrid的ajaxSelectOptions参数。例如,如果您需要将所选行的id作为额外的id
参数发送到由dataUrl
标识的Web方法,则可以使用函数形式的ajaxSelectOptions
的data
参数:
ajaxSelectOptions: {
type: "GET", // one need allows GET in the webmethod (UseHttpGet = true)
contentType: 'application/json; charset=utf-8',
dataType: "json",
cache: false,
data: {
id: function () {
return JSON.stringify($("#list").jqGrid('getGridParam', 'selrow'));
}
}
}
因为在上面的代码中使用了参数dataType: "json"
,所以您应该修改中buildSelect
的第一行
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
...
至
buildSelect: function (data) {
var response = $.parseJSON(data.d);
...
此外,由于您使用了$.parseJSON(data.d)
行,我可以假设您以错误的方式从Web方法返回数据。通常,web方法的返回值类型应为类。您不应该包含对返回对象的任何手动序列化调用。相反,有些人误解了这一点,并将string
声明为Web方法的返回类型。他们通过调用DataContractJsonSerializer
或JavaScriptSerializer
手动进行JSON序列化。因此,作为字符串返回的手动序列化数据将被再次序列化一次。这就是为什么您可以对$.parseJSON
:var retValue = $.parseJSON(data); var response = $.parseJSON(retValue.d);
进行两次调用的原因。如果您将在ajaxSelectOptions
中使用dataType: "json"
,并且如果您在web方法中对JSON执行不手动序列化,并且只按原样重新调整对象,那么您将需要对$.parseJSON
进行无调用。您可以直接使用data.d
:
buildSelect: function (data) {
var response = data.d;
...