c# - DELETE 方法似乎什么都不做

标签 c# http asp.net-core routing

我使用不同的 http 方法获得了到同一模板的两条路由:

routes.MapRoute(
    name: "GetPostToShow",
    template: "posts",
    defaults: new { controller = "Home", action = "GetPostToShow" },
    constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });
routes.MapRoute(
    name: "DeletePost",
    template: "posts",
    defaults: new { controller = "Home", action = "DeletePost" },
    constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "DELETE" }) });

两个 Action 获取相同的查询参数并返回不同的 View

public async Task<IActionResult> GetPostToEdit(int postId)
    ...//load post from database and send it to view
    return View("EditPost", post);

public async Task<IActionResult> DeletePost(int postId)
    ...//locate post in database and remove it, redir to Index then
    return RedirectToAction("GetIndex");

以及在表单中实现的 DELETE 方法(防伪关闭测试原因):

<form asp-antiforgery="false" method="delete" role="form">
    <input hidden type="number" name="postId" value="@Model.Id"/>
        <input type="submit" class="btn btn-default" value="Delete" />
</form>

因此,当我提交此表单时,我希望被重定向到我的索引页面或显示错误消息,但实际上什么也没有发生。它似乎只是重新加载页面。我该怎么做才能正常工作?

更新: 我用谷歌搜索,发现 DELETE 并不意味着要在表单中使用。当然,我可以只创建 @Html.RouteLink 重定向,但我仍然想使用 DELETE 方法。如何创建使用该方法发出请求的按钮?

最佳答案

正如您所确定的,HTML 表单仅支持 GET 和 POST,不支持 DELETE 或任何其他 HTTP 动词。如果您想通过 DELETE 发送,您唯一的选择是发出 AJAX 请求。

您只需将处理程序绑定(bind)到表单的提交事件,调用 event.preventDefault() 来阻止正常的表单提交,然后改为通过 AJAX 发送请求:

document.getElementById('#myForm').addEventHandler('submit', function (event) {
    event.preventDefault();
    // send via AJAX with DELETE as the method
});

关于c# - DELETE 方法似乎什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376356/

相关文章:

c# - LINQ:如何使用 IQueryable() 选择特定列

c# - 无法从 ASP.NET MVC4 导入 ServiceReference1

android - Retrofit2:使用正文与查询

javascript - 调用时禁用 View 组件中的所有内容

azure - 您可以在 Azure Service Fabric 项目中使用 project.json 吗?

c# - 在 asp.net core 中读取配置并将其加载到自定义对象中时遇到问题

c# - 如何检测对象的变化?

c# - oData 中的集合名称列表

node.js - 如何在不使用端口的情况下在同一域上的 Apache 旁边运行 node.js 应用程序

c# - 使用 NancyFX 自托管的分块压缩响应