我有以下情况
function Insert(name, parentID) {
$.ajax({
type: "POST",
url: "topic.aspx/Insert",
data: JSON.stringify({
"name": name,
"parentID": undefined
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function (msg) { alert(msg.responseText); }
});
}
C#看起来像这样
[WebMethod]
public static int Insert(string name, int? parentID)
{
GM.KnowledgeBase.Business.Topics topics = new GM.KnowledgeBase.Business.Topics();
return topics.Insert(name, parentID);
}
当parentID为null或未定义时,我得到"无效的Web服务调用,缺少参数"的值。是否有更优雅的方法来解决此问题,然后将参数作为字符串传递并检测字符串是否为空?
答案 0 :(得分:1)
未定义时不要传递它?
function Insert(name, parentID) {
var data = { name: name };
if(parentID)
data.parentID = parentID
$.ajax({
type: "POST",
url: "topic.aspx/Insert",
data: data,
// etc...
});
}
或者如果您的网络方法可以解析null
,则应执行以下操作:
data: JSON.stringify({
"name": name,
"parentID": parentID || null
}),
答案 1 :(得分:0)
由于您将参数声明为可为空(在插入函数中),您可以安全地从ajax函数发送它
$.ajax({
type: "POST",
url: "topic.aspx/Insert",
data: JSON.stringify({
"name": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function (msg) { alert(msg.responseText); }
});
}
在此之后,您将在insertID函数中看到parentID参数
的空值