I’m using ajax for calling a delete action in my web api controller.I have problem with two types of calling my api with Ajax.
Here is my api code:
[Authorize]
public class AttendancesController : ApiController
{
private readonly ApplicationDbContext _context;
public AttendancesController()
{
_context = new ApplicationDbContext();
}
[HttpDelete]
public IHttpActionResult Delete(int gigId)
{
var userId = User.Identity.GetUserId();
var attendance = _context.Attendances.SingleOrDefault(a => a.GigId == gigId && a.AttendeeId == userId);
if (attendance == null)
{
return NotFound();
}
_context.Attendances.Remove(attendance);
_context.SaveChanges();
return Ok();
}
}
When I use this javascript code my action call and everything is ok.
$.ajax({
url: "/api/attendances/?gigId=" + button.attr("data-gig-id"),
method: "DELETE"
})
.done(function () {
button
.removeClass("btn-info")
.addClass("btn-default")
.text("Going ?");
})
.fail(function () {
alert("Something is failed!");
});
But when I use this code, my api doesn’t call and the fail callback method executes.
$.ajax({
url: "/api/attendances/" + button.attr("data-gig-id"),
method: "DELETE"
})
.done(function () {
button
.removeClass("btn-info")
.addClass("btn-default")
.text("Going ?");
})
.fail(function () {
alert("Something is failed!");
});
I’m confused because the second calling approach used in a learning movie and it works.
Can you explain this problem?
2
Answers
I find the solution
The problem is in the definition of Delete method, according to the WebApiConfig.cs the acceptable route has this pattern: api/{controller}/{id}
So the input variable name should be id instead of gigId.
This is right code:
You should add a route to the action in your controller