MVC jQuery的AJAX调用与输入参数
问题描述:
在控制器我有以下动作调用控制器上的动作时,我面临一个问题:
[HttpPost]
public ActionResult UpdateData(string month)
{
return Json(new { success = true, message = "Hello world" });
}
在Ajax调用视图的样子:
$.ajax({
url: '@Url.Action("UpdateData")',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
data: { },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
这个效果很好,但是当我想通过像
参数我得到一个错误,这个动作永远不会被调用。我只是没有看到它。
编辑:
好吧,我不得不通过JSON作为一个字符串:
data: "{month:'may'}"
我想我需要更多的睡眠:-)
答
你必须只是删除内容类型和更好如果你在URL中传递控制器名称:
$.ajax({
url: '@Url.Action("UpdateData","YourControllerName")',
dataType: "json",
type: "POST",
cache: false,
data: {month:'may'} ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
请注意,model-view-controller标签用于提供有关该模式的问题。没有为ASP.NET-MVC实现特定的标签。 –
你需要做的是删除'contentType:'application/json; charset = utf-8','并使用'data:{month:'may'}' –
它的工作原理,谢谢!我将在下次使用asp.net-mvc标签;-) – Alpine13