views:

3558

answers:

2

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! :)

+3  A: 

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

JD Conley
+7  A: 

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.

Dave Ward
Dave, you got credit for writing a good post, but didn't get voted as the best answer!?! Go figure. My team loves your blog and you introduced great techniques to us that we have used in production. Keep up the good work.
David Robbins
Mr. Robbins is correct, this should be the answer. Thank you.
Joe Behymer