Reputation: 2339
I am trying to use ajax to call a controller method and i am getting a internal server error.
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");
}
}
});
}
the controller looks like this:
[HttpPost]
public ActionResult User(int id, string comment)
{
var user = UserModel.GetPerson(id);
user.IsDeleted = true;
UserModel.UpdatePerson(user);
return RedirectToAction("ManageUsers");
}
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?
Upvotes: 0
Views: 11125
Reputation: 1410
This is not an exact answer for this question and I'm aware of that, but there was such a case that occured to me while I was trying to call controller method via AJAX call. I checked the controller method and I realized that I didn't put [AllowAnonymous]
after [HttpPost]
. Obviously it is required in my application because there are different cases for logged in users and anonymous users. Lack of this keyword caused AJAX not to hit controller method, maybe there is someone who is trying to do the same thing and see this answer.
Upvotes: 0
Reputation: 50523
Your object properties conflict with the arguments of the action
Object Properties
{
userId : id,
comments : $("#comment").val()
}
vs. Action Arguments
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.
Upvotes: 3
Reputation: 1722
Following on from Gabe's answer, I think you'll find you cant redirect to action from a ajax request. In your success callback you'll need to set the document.location to the url of the action you wish to redirect too. Currently the redirect to action is getting returned by mvc but not to your browser.
Callback
success: function (data) {
document.location = data.responseText;
}
Controller return
return Url.Action("ManageUsers", "Users").ToString();
Upvotes: 1