Asp.net-Core

如何從 ASP.NET Core 的 Razor 視圖中獲取 Url 中 id 的值

  • January 1, 1

我有一個簡單的 ASP.NET Core Web 應用程序,其中包含這樣的頁面http://localhost:5050/Posts/Create/3

在我的 Razor ViewViews/Posts/Create.cshtml中,我怎樣才能獲得值“3”,以便我可以創建一個類似的連結<a href="/Blogs/Details/3">« Back to Blog</a>

到目前為止,使用以下 Tag Helper 創建了連結,但我不知道該放什麼asp-route-id

<a asp-controller="Blogs" asp-action="Details" asp-route-id="" class="btn btn-default btn pull-right">« Back</a>

我只是使用預設的 mvc 路由:

app.UseMvc(routes =>
{
   routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");
});

我知道我可以從模型(即Model.Blog.BlogId)中獲取它,但我希望使用類似Request.Query["id"]in的東西從 Url 中獲取它Views/Post/Create.cshtml

我試過了asp-route-id="@Context.Request.Query["id"]

類似的東西Context.GetRouteData().Values["id"];

還有<http://www.blakepell.com/how-to-get-the-current-route-in-a-view-with-asp-net-5-mvc-6>

引用自:https://stackoverflow.com/questions/42046781