met.lord met.lord - 3 months ago 19
jQuery Question

Why is DELETE $.ajax call not caught by my controller?

I'm trying to delete an entity using AJAX. In my controller method I have:

[HttpDelete]
public ActionResult Delete(int id)
{
//Deletion logic
return Content("OK");
}


In the view I was making an AJAX call as follows:

$('#delete').click(function () {
if (confirm('Delete?')) {
var $link = $(this);
$.ajax({
url: this.href,
type: 'DELETE',
success: function (result) {
$link.parent().remove();
}
});
}
return false;
});


AJAX link is being built as:

@Html.ActionLink("Delete?", "Delete", new { id = Model.Id }, new { id = "delete", @class = "delete-link" })


The
Delete
action is not getting the request from the link, but if I access through the direct URL it actually works. Also, if I delete the
type: 'DELETE',
line leaving it unspecified and replace the Controller Action line
[HttpDelete]
with
[HttpGet]
it works too.

My point is given it's a
DELETE
method I wouldn't want to handle it as a
GET
request but I can't figure out if I'm missing something else.

I would love if any of you guys could help me out to understand why the controller action
Delete(int id)
is not catching the requests coming from the AJAX Link.

Thanks in advance.

Answer

It could be that IIS does not allow PUT and DELETE (see ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8)

Check your handlers in your Web.config

<system.webServer>
    <handlers>
           <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
           <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

This change did the trick for me.