5

I am using WebApi in a ASP.Net web application. I have a method in the controller called Delete and I want to access to this method by using jQuery's AJAX method. Below is my code:

[Authorize]
public int Delete(int proposalId)
{
    // logic here...     
}
$.ajax({
    url: "/Controller/Proposal/" + proposalId,
    type: "Post",
    contentType: "application/json",
    success: function() {
        bootbox.alert("Proposal deleted successfully.");
        ReloadGrid();
    },
    error: function() {
    }
});
RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "controller/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"></modules>
</system.webServer>

The problem is that when I am using POST it is executing another method which starts as Post. Can anyone please help me with this?

1
  • 1
    Try using DELETE instead of POST in ajax ex. type: "Delete" Commented Mar 18, 2015 at 13:52

2 Answers 2

7

Assuming this is accessing a REST API, you need to send a DELETE request by setting the appropriate type in your $.ajax call:

$.ajax({
    url: "/Controller/Proposal/" + proposalId,
    type: "DELETE", // <- Change here
    contentType: "application/json",
    success: function() {
        bootbox.alert("Proposal deleted successfully.");
        ReloadGrid();
    },
    error: function() {
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

delete request donot have any callback functions whether the deletion is success or not Yes they do - it works as any normal request based on the HTTP code of the response.
Hello Rory, Sorry it is not working as you proposed but is working when used like below.. url: "/Controller/Proposal/", type: "DELETE", data: JSON.stringify(proposalId), And [Authorize] public int Delete([FromBody] int proposalId) { }
-1

If you must use a custom method for deletion for example, you can always rely on setting HTTP attributes -- like so:

[HttpDelete]
[Route("api/Proposal")]
public IHttpActionResult Proposal(long id){
   ...
}

2 Comments

Sir if I am not wrong you are setting id as a parameter and not setting in Route that is wrong , right!
Four years later! Lol - It doesn't matter from where you get your indicator. It can be from a parameter, a route endpoint, a context header, a code in a bearrer token, what matters is the treatment it receives after you got it and before you use it. Never, ever, use what you receive without parsing it through your js cleaner, regex cleaner, sql cleaner, etc... it's tough, but it needs to be done!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.