Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of id in Url from Razor View in ASP.NET Core

I have a simple ASP.NET Core web application with a page like such http://localhost:5050/Posts/Create/3.

In my Razor View Views/Posts/Create.cshtml, how would I be able to get the value "3" so that I can create a link like <a href="/Blogs/Details/3">« Back to Blog</a>?

So far, created the link using the following Tag Helper, but I don't know what to put for asp-route-id:

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

I am just using the default mvc route:

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

I know I can get it from the Model (i.e., Model.Blog.BlogId), but I'm looking to get it from the Url using something like Request.Query["id"] in Views/Post/Create.cshtml.

I tried asp-route-id="@Context.Request.Query["id"].

like image 673
kimbaudi Avatar asked Feb 04 '17 23:02

kimbaudi


2 Answers

Something like that Context.GetRouteData().Values["id"]; ?

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

like image 158
Daboul Avatar answered Sep 18 '22 19:09

Daboul


Currently in ASP.NET Core 2.1 & 3.1 this works:

Context.Request.Query["id"]
like image 40
Fabian Avatar answered Sep 17 '22 19:09

Fabian