如何从ASP.NET Core中的Razor View获取Url中的id值

kim*_*udi 8 asp.net-core-mvc tag-helpers asp.net-core

我有一个简单的ASP.NET Core Web应用程序,其中包含这样的页面http://localhost:5050/Posts/Create/3.

在我的Razor View中Views/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">&laquo; Back</a>
Run Code Online (Sandbox Code Playgroud)

我只是使用默认的mvc路由:

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

我知道我可以从模型(即,得到它Model.Blog.BlogId),但我希望从URL得到它使用类似Request.Query["id"]Views/Post/Create.cshtml.

我试过了asp-route-id="@Context.Request.Query["id"].

Dab*_*oul 10

那样的东西Context.GetRouteData().Values["id"];

另外http://www.blakepell.com/how-to-get-the-current-route-in-a-view-with-asp-net-5-mvc-6

  • 你也可以使用`ViewContext.RouteData.Values ["id"]` (6认同)

foa*_*ahi 7

在 ASP.NET Core 3.1 & .NET 5 & .NET 6 中,这对我有用:

@Context.Request.RouteValues["id"]
Run Code Online (Sandbox Code Playgroud)


小智 6

目前在ASP.NET Core 2.1中,这有效:

Context.Request.Query["id"]
Run Code Online (Sandbox Code Playgroud)


小智 5

FWIW:我使用 @ViewContext.RouteData.Values["yourRouteId"]