C # custom data transfer objects from javascript PageMethods

I created a custom object that I would like to return to JSON for the javascript method. This object was created as a class in C #.

What is the best way to return this object from the PageMethod ([WebMethod] method, if you want) to the javascript onPageMethodCallback () function? I need to have access to the properties of this object through javascript and update the DOM according to (possibly using jQuery).

Thanks StackOverflow! :)

+6
json javascript ajax asp.net-ajax
source share
2 answers

ASP.NET AJAX on the server side will handle object serialization 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 PageMethod directly from jQuery, using basically the same method that JD is associated with. More specifically, here's a post about calling PageMethods with jQuery .

The server will serialize your return type as JSON, and you will 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 .d. This is a security feature added in 3.5 and is not available in version 2.0.

+12
source share

Here's a pretty extensive post on using JSON-serialized WebMethods from asmx with jQuery. That should 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 execute the AJAX bit, then you should take a look at the ScriptManager and ServiceReference, which create a javascript proxy for you. It is really powerful, and we successfully use it in some fairly large applications. Found in this article:

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

+3
source share

All Articles