我使用不同的 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/