将复杂对象作为参数发送给 Asp.Net PageMethod
我正在尝试将在 JavaScript 中创建的对象发送到 ASP.NET PageMethod。该对象反映了现有自定义业务对象的属性,因此我希望可以传递单个对象而不是每个属性的参数。尝试使用此方法时,我收到错误“未知的 Web 方法 SavePart”。Javascript
:
function() {
var pt = { Id: 1, Onhand: 20, LowPoint: 30, __type: 'Custom.Objects.Part'};
$.ajax({
type: 'POST',
url: 'partlist.aspx/SavePart',
data: JSON.stringify(pt),
contentType: 'application/json; charset: utf-8;'
dataType: 'json',
success: function(results) { alert('Success!'); }
});
}
代码隐藏:
<WebMethod()> _
Public Shared Function SavePart(pt as Custom.Objects.Part) as Boolean
Dim repo as new PartRepository()
return repo.Save(pt)
End Function
我正在使用另一个仅接受 int 的 PageMethod,并且效果很好。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我最终通过 jQuery ajax 命令以这种方式发送对象来解决我的问题:
这会自动序列化对象并将其返回到我的 WebMethod。当我尝试按原样发送对象时,出现错误“无效的 JSON 原语”。
I ended up solving my problem by sending the object this way through the jQuery ajax command:
this serialized the object automatically and returned it to my WebMethod. When i tried sending the object as is, i got an error saying "invalid JSON primitive".
您正在尝试将字符串传递给该方法。您需要接受该字符串,并使用 fx 对其进行反序列化。 JavascriptSerializer 或 JSON.NET
You are attempting to pass a string to the method. You will need to accept the string, and deserialize it with fx. JavascriptSerializer or JSON.NET
我知道这非常古老,但是当您使用它来找出问题所在时,它不是很直观。您非常接近,但我想添加更多内容,以防其他人以后想做同样的事情。这也适用于嵌套对象,我能说的一件事是 JS 变量中的 CASE 很重要,这些变量映射到页面方法上的 .NET POCO。
你的“答案”就是我要开始的地方。正如下面的评论所示,是的,您必须传递包裹在其页面方法变量名称中的对象。
我再说一遍,这是区分大小写的,不仅会在对象的名称上出现问题,还会在其属性上出现问题。因此,为了解决这个问题,我通常在 .NET 中创建 POCO 对象,然后将其复制到页面,这样我就知道名称、大小写等都是正确的。
像这样的东西:
POCO:
现在使用为页面方法定义的 POCO,完全复制该“模型”,就像 JS/AJAX 发布时所使用的那样,并对大小写敏感保持警惕。
页面方法(注意参数中的custobj):
I know this is incredibly old, but its not very intuitive when you're using this to figure out what the issues are. You are very close but I wanted to add a bit more to this in case someone else later wants to do the same thing. This works with nested objects as well, the one thing I can say is CASE matters in your JS variables that map to .NET POCOs on the page method.
Your "answer" is where I will start with. And as in the comments below it, yes you have to pass the object wrapped in its page method variable name.
Ill say it again, this is CASE-Sensitive, and can trip you up not just on the object's name but its properties as well. So to combat this I usually create my POCO object in .NET then copy that to the page so I know the names, capitalization and all are correct.
Something like this:
POCO:
Now with a defined POCO for page method, replicate that "model" exactly as it is for the JS/AJAX to post with, being vigilant about case-sensitivity.
Page Method (Note custobj in the parameters):