views:

743

answers:

4

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?

A: 

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
+4  A: 

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
Why not an aspx page?
LB
Because you don't need the full page lifecycle. An aspx page will cause of bunch of work to happen you don't need - it's wasteful.
Joel Coehoorn
+1 - This is definitely worth noting if he's doing several requests to the same function
John Rasch
Hmm... my basic text is right, but my link might be for the wrong json serializer.
Joel Coehoorn
+6  A: 

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/

John Rasch
how would you pass params tho?
LB
+2  A: 

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