Reputation:
I am trying to use ajax to send a delete request to ASP.NET MVC 5 framework. There is a single page with a single red button.
In the CustomersController :
[HttpDelete]
[Route("^/customers/delete/{id:int}")]
public ActionResult Delete(int id)
{
CarDealerContext ctx = new CarDealerContext();
// Delete customer with given id...
// If I get a get a breakpoint in here I will be a happy camper!
return View();
}
In the RouteConfig :
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
In the view I only have :
<input id="deleteBtn" class="btn btn-danger" type="button"
value="Delete" data-id="1"/>
This is the script i use when the deleteBtn is clicked :
// The script is loaded after Bootstrap and jQuery.
$("#deleteBtn").on("click", function (event) {
event.preventDefault();
var id = $("#deleteBtn").attr("data-id");
$.ajax({
url: "/customers/delete/" + id,
type: 'delete',
data: { id: id }
});
})
// The request sends http://localhost:61402/customers/delete/1
// and the response is 404...
All I want is to activate the Delete method in the CustomersController. I have tried pretty much everything in the Route(regex) attribute. The second I change the Method to [HttpGet] it works. Would also appreciate a good studying source on the subject.
Upvotes: 0
Views: 4760
Reputation: 3697
You need to enable these verbs in IIS (put, delete)
Iisexpress may need config file edit
Upvotes: 3
Reputation: 2031
Change your Action Method as follows:
[HttpGet]
public ActionResult Delete(int id)
{
//Your Code
}
Two points to note:
1) Instead of HTTPDelete, you should set an HTTPGet annotation because the request you're sending from your view is a GET request, not one that's conventionally understood as a delete operation type request.
2) This may not be required in your case but I thought I'd mention it anyhow. ASP.NET MVC prefers convention over configuration. You don't need to explicitly set that route. The default route in the RouteConfig file will point to your method.
This would be the default configuration in the RouteConfig file:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = request to this Action Method (if you don't have it, it's probably a good idea UrlParameter.Optional }
);
Upvotes: 0