7

Without using any third party tools, what is the ideal way to provide JSON response data?

I was thinking of having an ASPX application page to just return the json string response. Any ideas?

LB.
  • 12,272
  • 21
  • 60
  • 99

4 Answers4

10

The simplest way is to create a method with the [WebMethod] attribute, and the response will automatically be JSON serialized. Try it yourself:

[WebMethod]
public static string GetDateTime()
{
    return DateTime.Now.ToString();
}

And the Ajax call URL would be:

Page.aspx/GetDateTime

Edit:

To pass parameters, just add them to the function:

[WebMethod]
public static int AddNumbers(int n1, int n2)
{
    return n1 + n2;
}

I'm using jQuery so the data: object would be set with:

data: "{n1: 1, n2: 2}",

Also note that the JSON object returned will look like this:

{"d":[3]}

The extra "d" in the data is explained here: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

Community
  • 1
  • 1
John Rasch
  • 57,880
  • 19
  • 101
  • 136
8

Not an aspx page, but maybe an ashx handler. To make this easier, .Net 3.5 has serialization support for JSON built in.

Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
2

Look into the JavascriptSerializer class that is provided by the ASP.NET framework. Generally you would use this in a Page Method or a WebMethod in a WebService to return an object serialized as JSON.

See the reference on MSDN here.

Adam Markowitz
  • 11,813
  • 3
  • 26
  • 21
0

I usually use a web service (asmx) with the ScriptService attribute and ScriptManager. There are some slight incompatibilities with some jQuery plugins, but it's nothing too serious and I don't have to deal with any manual serialization.

Tom Clarkson
  • 15,534
  • 2
  • 35
  • 46