开发者

What is the recommended method to read JSON data posted with JQuery AJAX in ASP.NET?

开发者 https://www.devze.com 2023-01-05 09:04 出处:网络
I currently have a JQuery Ajax method as below; $.ajax({ type:\"POST\", url: \"default.aspx/UpdateData\",

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.Read开发者_运维百科ToEnd();

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


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消