我有这个 Controller 方法:
public JsonResult List(int number) {
var list = new Dictionary <int, string> ();
list.Add(1, "one");
list.Add(2, "two");
list.Add(3, "three");
var q = (from h in list where h.Key == number select new {
key = h.Key,
value = h.Value
});
return Json(list);
}
在客户端,有这个 jQuery 脚本:
$("#radio1").click(function() {
$.ajax({
url: "/Home/List",
dataType: "json",
data: {
number: '1'
},
success: function(data) {
alert(data)
},
error: function(xhr) {
alert(xhr.status)
}
});
});
我总是收到错误代码 500。有什么问题吗?
谢谢
最佳答案
如果您看到实际的响应,它可能会说
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
您需要使用重载的 Json
构造函数来包含 JsonRequestBehavior.AllowGet
的 JsonRequestBehavior
,例如:
return Json(list, JsonRequestBehavior.AllowGet);
这是它在示例代码中的样子(请注意,这也会将您的 int
更改为 string
,否则您会收到另一个错误)。
public JsonResult List(int number) {
var list = new Dictionary<string, string>();
list.Add("1", "one");
list.Add("2", "two");
list.Add("3", "three");
var q = (from h in list
where h.Key == number.ToString()
select new {
key = h.Key,
value = h.Value
});
return Json(list, JsonRequestBehavior.AllowGet);
}
关于javascript - ASP.NET MVC JsonResult 返回 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3113952/