使用AJAX通过Web Api Delete方法调用

时间:2015-03-18 13:50:12

标签: jquery asp.net asp.net-web-api jquery-ajaxq

我在ASP.Net Web应用程序中使用WebApi。我在控制器中有一个名为Delete的方法,我想通过使用jQuery的AJAX方法来访问这个方法。 以下是我的代码:

[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>

问题在于,当我使用POST时,它正在执行另一个以Post开头的方法。有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:6)

假设这是访问REST API,您需要在DELETE来电中设置相应的type来发送$.ajax请求:

$.ajax({
    url: "/Controller/Proposal/" + proposalId,
    type: "DELETE", // <- Change here
    contentType: "application/json",
    success: function() {
        bootbox.alert("Proposal deleted successfully.");
        ReloadGrid();
    },
    error: function() {
    }
});

答案 1 :(得分:-1)

例如,如果必须使用自定义方法进行删除,则可以始终依赖于设置HTTP属性 - 如下所示:

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