Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom C# data transfer objects from javascript PageMethods

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

like image 827
JoeB Avatar asked Jan 20 '09 06:01

JoeB


1 Answers

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.

like image 148
Dave Ward Avatar answered Sep 23 '22 14:09

Dave Ward