C# 将 jquery json 传入 asp.net httphandler
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12401239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass jquery json into asp.net httphandler
提问by ailmcm
Just don't get it what i'm doing wrong.. i've been looking for dozens of similar questions, yet still got misunderstandings... when i call CallHandler function from JS, i always get 'Request Failed' alert. please help me.
只是不明白我做错了什么......我一直在寻找几十个类似的问题,但仍然有误解......当我从 JS 调用 CallHandler 函数时,我总是收到“请求失败”警报。请帮我。
JS/Jquery:
JS/Jquery:
function CallHandler() {
$.ajax({
url: "DemoHandler.ashx",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: "json",
data: [{"id": "10000", "name": "bill"},{"id": "10005", "name": "paul"}],
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
asp.net c# code behind:
后面的asp.net c#代码:
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string jsonString = HttpContext.Current.Request.Form["json"];
List<Employee> emplList = new List<Employee>();
emplList = jsonSerializer.Deserialize<List<Employee>>(jsonString);
string resp = "";
foreach (Employee emp in emplList){
resp += emp.name + " \ ";
}
context.Response.Write(resp);
}
public class Employee
{
public string id { get; set; }
public string name { get; set; }
}
采纳答案by Adrian Iftode
Try
尝试
data: JSON.stringify([{id: "10000", name: "bill"},{id: "10005", name: "paul"}])
editI removed the quotes from the property names
编辑我从属性名称中删除了引号
Also, the JSON string needs to be read in other way
此外,JSON 字符串需要以其他方式读取
string jsonString = String.Empty;
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
An working solution
一个有效的解决方案
public void ProcessRequest(HttpContext context)
{
var jsonSerializer = new JavaScriptSerializer();
var jsonString = String.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
var emplList = jsonSerializer.Deserialize<List<Employee>>(jsonString);
var resp = String.Empty;
foreach (var emp in emplList)
{
resp += emp.name + " \ ";
}
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(jsonSerializer.Serialize(resp));
}
public class Employee
{
public string id { get; set; }
public string name { get; set; }
}
public bool IsReusable
{
get
{
return false;
}
}

