How to get value of id in Url from Razor View in A

2020-08-11 11:05发布

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"].

8条回答
对你真心纯属浪费
2楼-- · 2020-08-11 11:21

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

Context.Request.Query["id"]
查看更多
疯言疯语
3楼-- · 2020-08-11 11:21

in ASP.NET Core 3.1 this works for me:

@Context.Request.RouteValues["id"]
查看更多
ゆ 、 Hurt°
4楼-- · 2020-08-11 11:23

FWIW: I use @ViewContext.RouteData.Values["yourRouteId"]

查看更多
SAY GOODBYE
5楼-- · 2020-08-11 11:23

For aspcore 2.1, use: HttpContextAccessor.HttpContext.Request.Query["id"]

查看更多
男人必须洒脱
6楼-- · 2020-08-11 11:28

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

查看更多
对你真心纯属浪费
7楼-- · 2020-08-11 11:29

This what I have used which is simple c# code works with .net core and pure MVC also:

 var reqUrl = Request.HttpContext.Request;
 var urlHost = reqUrl.Host;
 var urlPath = reqUrl.Path;
 var urlQueryString= reqUrl.QueryString;
 if (urlQueryString == null)
 {
 ViewBag.URL= urlHost + urlPath;
 }
 else
 {
 ViewBag.URL= urlHost + urlPath + urlQueryString;
 }
查看更多
登录 后发表回答