在我的 Controller 中我有
public JsonResult GetInfo(string id)
在我的js中
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/Incidents/GetInfo",
data: { id: "777" },
cache: false,
dataType: "json",
success: function (response) {
//etc....
jquery ajax 错误委托(delegate)被执行。如果我使用
data: { "777" },
没有错误,但值没有被传递。这应该很容易,但我正在用头撞墙。也许我不允许将字符串传递给 Controller 的操作?
我在这里做错了什么?
最佳答案
您正在指示 application/json
请求,并且您正在发送 application/x-www-form-urlencoded
请求。因此,您必须在两种编码参数的方法中选择一种,而不是混合使用它们。
application/x-www-form-urlencoded
:
$.ajax({
type: "POST",
url: "/Incidents/GetInfo",
data: { id: "777" },
cache: false,
dataType: "json",
...
});
application/json
:
$.ajax({
type: "POST",
url: "/Incidents/GetInfo",
contentType: 'application/json, charset=utf-8',
data: JSON.stringify({ id: "777" }),
cache: false,
dataType: "json",
...
});
JSON.stringify
方法原生内置于现代浏览器中,用于将 javascript 文字转换为 JSON 字符串,这就是我们指示要发送请求的字符串。如果您必须支持旧版浏览器,您可以包含 json2.js将脚本添加到包含此方法的页面。
顺便说一句,不需要 dataType: "json"
设置,因为服务器会将正确的 Content-Type
header 设置为 application/json
并且 jQuery 足够聪明,可以使用它。
作为第二个附注,您确实不想在 javascript 文件中硬编码这样的 url:url: "/Incidents/GetInfo"
。您想要的是在生成 url 时使用 url 帮助程序:url: "@Url.Action("GetInfo", "Incidents")"
。
关于asp.net-mvc - Asp.net MVC Controller 操作字符串参数未传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8145627/