I have a custom HtmlHelper;
public static MvcHtmlString DeleteEmployeeOtherLeave(this HtmlHelper html, string linkText, Leave _leave)
{
string url = string.Format("/Payroll/Delete?_employeeOtherLeaveId={0}", _leave.LeaveId.ToString());
return html.RouteLink(linkText, "Default",
new { _employeeOtherLeaveId = _leave.LeaveId, action = "Delete" },
//new { @class = "delete-link" }
new { onclick = "$.ajax({url: this.href, type: 'DELETE', success: function(result) {$('#wholepage').html(result);}}); return false;" }
}
As you can see I have a long string for my onclick event for my RouteLink command.
I want to put this in some unobtrusive Javascript, and then put in some extra javascript for a confirmation popup.
So if I comment out the onclick event and uncomment out the class, I intend to use instead the following Javascript function
$('#delete-link').click(function () {
var flag = confirm('Are you sure you wish to delete this item?');
if (flag == true) {
$.ajax({
url: this.href,
type: 'DELETE',
success: function (result) {
// update some DOM element with the result returned by the
// server. So supposing that you have some <div id="someContainer">
// that will contain the part of the DOM you want updated:
$('#wholepage').html(result);
}
});
}
return false;
});
The problem then is that a get the error;
System.Web.HttpException: A public action method ‘Delete’ was not found on controller ‘SHP.Controllers.PayrollController’
But this is a public method, so why should I get that?
[AcceptVerbs(HttpVerbs.Delete)]
public ActionResult Delete(int _employeeOtherLeaveId)
{
EmployeeOtherLeaf.Delete(_employeeOtherLeaveId);
return RedirectToAction("Payroll");
}
Some people have pointed out that this.url will have the wrong value. This appears to be the case, Firebug it reports that this.href is undefined.
So I change the helper method as below;
public static MvcHtmlString DeleteEmployeeOtherLeave(this HtmlHelper html, string linkText, Leave _leave)
{
string url = string.Format("/Payroll/Delete?_employeeOtherLeaveId={0}", _leave.LeaveId.ToString());
return html.RouteLink(linkText, "Default",
new { _employeeOtherLeaveId = _leave.LeaveId, action = "Delete" },
new { onclick = "DeleteRow('" + url + "')" }
}
The javascript function looks like this;
function DeleteRow(url) {
$.ajax({
url: url,
type: 'DELETE',
success: function (result) {
$('#wholepage').html(result);
}
});
return false;
}
I still get the same error.
Your issue is that jQuery does not support making Delete calls via Ajax so it is doing a GET or a POST which is not found on the controller because you are restricting to delete.
See here on how to solve this issue:
http://homework.nwsnet.de/news/9132_put-and-delete-with-jquery
Hope this helps
Addition:
I have looked into this more and the latest jQuery may support it but states:
The way that MVC gest around flakey browser support is to add a hidden field to forms that delete called _method and give it a value of delete
So you may wish to add to your ajax code: