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?
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
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/
Not an aspx page, but maybe an ashx handler. To make this easier, .Net 3.5 has serialization support for JSON built in.
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.
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