我在 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">
我可能在这里做错了什么?为什么没有正确解析路由?
最佳答案
是的,您必须明确地删除 id
,因为您已经知道了。这是因为 id
是一个环境值,这就是它在链接生成期间使用的原因。
关于为什么会这样:
一般而言(常规或属性路由),当要对路由进行排序时,最具体的路由需要排在不太具体的路由之前,并且段数较多的路由排在段数较少的路由之前。因此,在您的场景中,路线 delete/{id:int}
将被自动安排在 delete
之前。现在,由于 id
的值是环境值,第一个路由的条件得到满足,因此您会看到以这种方式生成的链接,因此要修复它,您需要清除它。
关于c# - 路由中带有 id 的 ASP.NET Core 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404619/