我在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开头的方法。有人可以帮我这个吗?
答案 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){
...
}