views:

47

answers:

2

I currently have a JQuery Ajax method as below;

$.ajax({
 type:"POST",
 url: "default.aspx/UpdateData",
 data: jsonString,
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function(msg){
  alert('saved');
 }
});

In the ASP.NET UpdateData method I'm using;

System.IO.StreamReader sr = new  System.IO.StreamReader(Request.InputStream);
string line = sr.ReadToEnd();

I will then serialise this data using DataContractJsonSerializer.

Is using Request.InputStream the right way to read the JSON data? Can I retrieve it as a method parameter, or any other way that may be considered better?

Thanks

A: 

You should send the JSON data in a POST variable. Then all you would have to do is access the request variable collection and pass the value into the parse method.

Adam Pope
+1  A: 

You can retrieve the data posted as a method parameter:

JS:

$.ajax({
    url: "default.aspx/UpdateData"
    data: '{ testString: "test", testInt: 123 }',
    ...
});

default.aspx:

[WebMethod]
public static void UpdateData(string testString, int testInt)
{
    ...
}

I would definitely recommend this approach as opposed to parsing the posted JSON. You can get a more complete example here: jQuery and ASP.NET AJAX PageMethods (see the second example)

Sean Amos
Sean thanks for that. But what if my JSON was an array like; {"Location": [{"lat":453,"lng":235},{"lat":235,"lng":245}]} In this case I can't use the parameters right?
Sivakanesh
Actually, yes you can. The framework will deserialize complex types and cast them as the specified parameter type, not just basic strings and ints.Not sure if I'm supposed to put code in a commenet, but in its simplest form:eg:public static void UpdateData(Dictionary<string, int>[] locations) {}This would be easier to work with if you had a "Location" class with the properties "lat" and "lng".eg:public static void UpdateData(List<Location> Locations) {}{ lat: 1, lng: 1 } would deserialize into a new instance of class Location, and an array would deserialize into a collection.
Sean Amos
That was it Sean. My quick test using a Location object to receive the JSON data works great. Thanks.
Sivakanesh