【问题标题】:Call by WebApi Delete method using AJAX使用 AJAX 通过 WebApi Delete 方法调用
【发布时间】:2015-05-21 08:17:01
【问题描述】:

我在 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 开头的方法。谁能帮我解决这个问题?

【问题讨论】:

  • 尝试在 ajax ex 中使用 DELETE 而不是 POSTtype: "Delete"

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


【解决方案1】:

假设这是访问 REST API,您需要通过在 $.ajax 调用中设置适当的 type 来发送 DELETE 请求:

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

【讨论】:

  • delete request donot have any callback functions whether the deletion is success or not 是的,他们会这样做——它可以像任何基于响应的 HTTP 代码的正常请求一样工作。
  • 没问题,很乐意提供帮助。
  • 您好,Rory,对不起,它没有按照您的建议工作,但在使用时可以按如下方式工作.. url:“/Controller/Proposal/”,类型:“DELETE”,数据:JSON.stringify( proposalId), 和 [Authorize] public int Delete([FromBody] int proposalId) { }
【解决方案2】:

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

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

【讨论】:

  • 先生,如果我没记错的话,您将 id 设置为参数,而不是在错误的 Route 中设置,对!
猜你喜欢
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
  • 2012-10-27
相关资源
最近更新 更多