1

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
met.lord
  • 618
  • 2
  • 9
  • 35

2 Answers2

1

IIS is blocking your [HttpDelete] method.

Add this in your web.config

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43
0

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.

Community
  • 1
  • 1
Nico
  • 3,542
  • 24
  • 29
  • It didn't work for me. 404. The only way so far I've found for it to work is decorate Controller action as [HttpGet] and deleting type line from Ajax call. – met.lord Aug 09 '16 at 09:39
  • How do your `handlers` section look like in your Web.config? – Nico Aug 09 '16 at 09:41
  • You were right about IIS. I did what @CristiPufu suggested and it worked. Thanks. – met.lord Aug 09 '16 at 09:47