[英]Ajax Call to ASP.NET MVC controller
jQuery 代码为:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '/myURL',
contentType: "application/json",
async: true,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
ASP.NET MVC controller
[HttpPost]
public async Task<ActionResult> Test(string myValue)
{
return Json("something");
}
我打了 controller 但myValue
是 null。
任何想法?
谢谢,
在视图端脚本中,应使用myValue
参数名称使绑定正常工作:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '@Url.Action("Test", "Home")',
contentType: "application/json",
async: true,
type: "POST",
data: { myValue: JSON.stringify(props) },
dataType: "json",
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
在 controller 侧:
[HttpPost]
public async Task<ActionResult> Test(string myValue)
{
var data = JsonConvert.DeserializeObject(myValue);
// TODO: ...
return Json("Success");
}
在上面的代码中使用了@Url.Action("Test", "Home")'
,它应该被正确的url
替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.