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

时间:2017-02-04 23:19:37

标签: asp.net-core asp.net-core-mvc tag-helpers

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

在我的剃刀视图Views/Posts/Create.cshtml中,我如何才能获得价值&#34; 3&#34;这样我就可以创建像<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>

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

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

我知道我可以从模型中获取它(即Model.Blog.BlogId),但我希望在Request.Query["id"]中使用类似Views/Post/Create.cshtml的内容从Url中获取它。

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

8 个答案:

答案 0 :(得分:8)

类似Context.GetRouteData().Values["id"];的内容?

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

答案 1 :(得分:5)

当前在ASP.NET Core 2.1中有效:

Context.Request.Query["id"]

答案 2 :(得分:2)

在Asp.Net Core 2.2中,看起来只有语句“ @ ViewContext.RouteData.Values [” id“]”会从类似“ https://localhost:44356/Administration/AddUser/0”的链接中获取ID。 如果您拥有这样的网址“ https://localhost:44356/Administration/AddUser/0?status=False”,并且想要获取“状态”的值,则可以使用“ @ Context.Request.Query [“状态”]”

答案 3 :(得分:1)

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

答案 4 :(得分:1)

使用[FromRoute]实现相同的功能。

@页面“ myaccount / {id}”

@function{
  [FromRoute]
  public string Id {get;set;}
}

答案 5 :(得分:0)

对于aspcore 2.1,请使用:HttpContextAccessor.HttpContext.Request.Query["id"]

答案 6 :(得分:0)

这是我使用的简单的c#代码,也可以与.net核心和纯MVC一起使用:

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

答案 7 :(得分:0)

在ASP.NET Core 3.1中对我有用:

@Context.Request.RouteValues["id"]