Custom C# data transfer objects from javascript PageMethods

人盡茶涼 提交于 2020-01-22 12:32:13

问题


I've created a custom object that I'd like to return in JSON to a javascript method. This object was created as a class in C#.

What's the best way to return this object from a PageMethod ([WebMethod] if you like) to a javascript onPageMethodCallback() function? I need to be able to access the properties of this object via javascript and update the DOM according (possibly using jQuery).

Thank you StackOverflow! :)


回答1:


ASP.NET AJAX on the server side will handle serializing the object for you. For example:

public class Name
{
  public string FirstName;
  public string LastName;
}

[WebMethod]
public Name GetName()
{
  Name name = new Name();

  name.FirstName = "Dave";
  name.LastName = "Ward";

  return name;
}

You can then call the PageMethod directly from jQuery using basically the same method that JD linked to. More specifically, here's a post about calling PageMethods with jQuery.

The server will serialize your return type as JSON and you'll be able to access the properties of the Name class as expected. In this example, msg.d.FirstName and msg.d.LastName.

Just watch out for the .d. It's a security feature added in 3.5, and isn't present in 2.0.




回答2:


Here's a pretty extensive post on the subject of using JSON serialized WebMethods from an asmx with jQuery. It ought to do the trick.

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

If you want to use ASP.NET AJAX instead of jQuery to do the AJAX bit then you should have a look at the ScriptManager and ServiceReference which create a javascript proxy for you. It's really powerful and we use it successfully in some pretty big apps. Found this article:

http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx



来源:https://stackoverflow.com/questions/460280/custom-c-sharp-data-transfer-objects-from-javascript-pagemethods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!