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

╄→尐↘猪︶ㄣ 提交于 2019-12-12 10:36:46

问题


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


回答1:


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




回答2:


Currently in ASP.NET Core 2.1 this works:

Context.Request.Query["id"]



回答3:


It looks like in Asp.Net Core 2.2 only the statement "@ViewContext.RouteData.Values["id"]" will get the id from a link like this "https://localhost:44356/Administration/AddUser/0". If you have a url like this one "https://localhost:44356/Administration/AddUser/0?status=False" and you want to get the value of "status" you can use "@Context.Request.Query["status"]"




回答4:


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




回答5:


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




回答6:


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;
 }


来源:https://stackoverflow.com/questions/42046781/how-to-get-value-of-id-in-url-from-razor-view-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!