【问题标题】:ASP.NET Core form with id in the route路由中带有 id 的 ASP.NET Core 表单
【发布时间】:2016-11-19 03:59:25
【问题描述】:

我在 ASP.NET Core 1.0.0 上的路由和表单有一个小问题。我有以下操作:

[Route("delete/{id:int}")]
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
    Post post = await _postsRepository.GetPost(id);
    return View(new DeletePostViewModel
    {
        PostId=post.Id,
        Title=post.Title
    });
}

[Route("delete"),HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> Delete([FromForm]DeletePostViewModel vm,string option)
{
    if (option == "Delete")
        await _postsRepository.DeletePost(vm.PostId);
    return RedirectToAction("Index");
}

在我看来,我有以下几点:

<form asp-action="Delete" asp-controller="AdminPosts" asp-area="Admin" method="post" role="form">
    <div class="form-group">
        <input type="hidden" asp-for="PostId"/>
        <label asp-for="Title"></label>
        <input type="text" asp-for="Title" class="form-control" readonly="readonly"/>
    </div>
    <p>
        <input type="submit" name="option" value="Delete" class="btn btn-danger" />
        <input type="submit" name="option" value="Cancel" class="btn btn-default" />
    </p>
</form>

但它不能正确解析路由。我为表单发布获得的路线也有 id,因此它不能解析 id。我必须将 id 添加到表单方法中:

[Route("delete/{id:int}"),HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id,[FromForm]DeletePostViewModel vm,string option)

或者我必须以 taghelper 的形式明确删除 id:

<form asp-action="Delete" asp-controller="AdminPosts" asp-area="Admin" asp-route-id="" method="post" role="form">

我在这里可能做错了什么?为什么不能正确解析路由?

【问题讨论】:

  • 我不建议对删除命令使用 HTTP GET...
  • @JeremyHolovacs 执行删除操作的是 POST...
  • 嗯,是的,看起来像。抱歉,我以为这是 Web api REST 调用

标签: c# asp.net-mvc routes asp.net-core


【解决方案1】:

是的,您必须明确删除id,因为您已经知道了。这是因为id 是一个环境值,这就是在链接生成期间使用它的原因。

关于为什么会这样
通常(常规或属性路线),当要对路线进行排序时,最具体的路线需要在不太具体的路线之前出现,并且段数较多的路线需要在段数较少的路线之前出现。因此,在您的场景中,路线delete/{id:int} 将被自动排序到delete 之前。现在,由于id 的值是环境值,因此满足第一条路由的条件,因此您会看到以这种方式生成的链接,因此要修复它,您需要清除它。

【讨论】:

    猜你喜欢
    • 2018-02-17
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2010-10-20
    • 2017-09-11
    • 2015-03-18
    相关资源
    最近更新 更多