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! :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With