MVC Ajax调用控制器方法 [英] MVC ajax calling controller method
问题描述
我正在尝试使用Ajax调用控制器方法,并且出现内部服务器错误.
I am trying to use ajax to call a controller method and i am getting a internal server error.
jquery看起来像这样:
The jquery looks like this:
function user(id) {
alert(id+" "+$("#comment").val());
var param = {
userId : id,
comments : $("#comment").val()
};
$.ajax({
url: "/Admin/User",
contentType: "application/x-www-form-urlencoded",
type: "POST",
datatype: "json",
data: param,
error: function (xmlHttpRequest, errorText, thrownError) {
alert(xmlHttpRequest+"|"+errorText+"|"+thrownError);
},
success: function (data) {
if (data != null) {
alert("success");
}
}
});
}
控制器看起来像这样:
[HttpPost]
public ActionResult User(int id, string comment)
{
var user = UserModel.GetPerson(id);
user.IsDeleted = true;
UserModel.UpdatePerson(user);
return RedirectToAction("ManageUsers");
}
看起来代码甚至都没有到达控制器. user(id)
中的第一个警报被触发.有人看到这里发生了什么吗?
It looks like the code isnt even getting to the controller. the 1st alert in user(id)
is being triggered. Does anyone see whats going on here?
推荐答案
您的对象属性与操作的参数冲突
Your object properties conflict with the arguments of the action
对象属性
{
userId : id,
comments : $("#comment").val()
}
与动作参数
int id, string comment
尝试更改它们以使其匹配,例如:
Try changing them to match, so for example:
public ActionResult User(int userId, string comments) { ... }
请注意,您将无法从异步请求重定向到操作.有点失败的目的.您需要在回调上进行重定向.
Please note you're not going to be able to redirect to action from an asynchronous request. It kind of defeats the purpose. You would need to redirect on a callback.
这篇关于MVC Ajax调用控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!