使用jquery .ajax传递可为空的参数(Pass a nullable parameter using jquery .ajax)

编程入门 行业动态 更新时间:2024-10-20 01:35:03
使用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 }),

更多推荐

本文发布于:2023-07-23 18:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   参数   ajax   jquery   nullable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!