使用jquery .ajax传递可为空的参数(Pass a nullable parameter using jquery .ajax)
我有以下情况
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服务调用,缺少参数值”。 是否有更优雅的方法来解决此问题,然后将参数作为字符串传递并检测字符串是否为空?
I have a following situation
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); } }); }And C# looks like this
[WebMethod] public static int Insert(string name, int? parentID) { GM.KnowledgeBase.Business.Topics topics = new GM.KnowledgeBase.Business.Topics(); return topics.Insert(name, parentID); }When parentID is null or undefined I get "Invalid web service call, missing value for parameter". Is there a more elegant way to solve this issue other then passing a parameter as a string and detecting if string is empty?
最满意答案
如果没有定义,请不要通过它?
function Insert(name, parentID) { var data = { name: name }; if(parentID) data.parentID = parentID $.ajax({ type: "POST", url: "topic.aspx/Insert", data: data, // etc... }); }或者如果你的webmethod可以解析null ,这应该做:
data: JSON.stringify({ "name": name, "parentID": parentID || null }),Don't pass it when it's not defined?
function Insert(name, parentID) { var data = { name: name }; if(parentID) data.parentID = parentID $.ajax({ type: "POST", url: "topic.aspx/Insert", data: data, // etc... }); }or if your webmethod can parse null, this should do:
data: JSON.stringify({ "name": name, "parentID": parentID || null }),更多推荐
发布评论