ASP.NET MVC3 AJAX POST: result are rendered in browser instead of being executed
Imagine I have an HTML table containing several rows with items. For each item I generate a "delete" button like this:
<% using (Ajax.BeginForm("Delete", "MyController", new { item.Id }, new AjaxOptions { HttpMethod="POST" })) { %>
<input type="submit" class="deletebutton" value="Delete" />
<% } %>
The corresponding action looks like this:
[HttpPost]
public JavaScriptResult Delete(int id)
{
var item = _repository.GetById(id);
// [...] actually delete the item
var script = string.Format("OnItemDeleted({0},{1})", item.Id, new JavaScriptSerializer().Serialize(item.Name));
return JavaScript(script);
}
Finally, this is the Javascript function that should be called after executing Delete:
function OnItemDeleted(id, name) {
$('#errorlabel').text(name + " deleted successfully.");
$('#tr_item_' + id).fadeOut();
};
I got this from Steven Sanderson's book "Pro ASP.NET MVC 2 Framework" and saw it working in my project once. In the meantime, a lot of my code has been changed including an update to MVC开发者_运维百科 3 and for some reason it isn't working any more. After I click on the delete button, the action method is called correctly but after this the browser shows me the JavaScript result in the browser, for example:
OnItemDeleted(21,"Fancy Item 1234")
Strangely, I am also being redirected to Admin/MyController/Delete/{ItemId} although my Delete action is clearly stated as [HttpPost] and there is no GET action with the same name.
Do you have any idea what might cause this behaviour? Thanks in advance!
Figured it out: I was using the old Microsoft JavaScript libraries from MVC 2. Replacing those fixed the problem.
精彩评论