跟踪当前活动页面,或如何在视图中获取控制器和操作名称

Ser*_*rge 10 razor asp.net-core

我是ASP.NET Core的新手.我有一个导航菜单,我想跟踪活动项目.我的想法是使用动作和控制器名称作为导航键:

在此输入图像描述

问题是我不知道如何在_Layout.cshtml视图中获取动作和控制器名称...

我试过了,ViewContext.ActionDescriptor.DisplayName但它渲染了这样的东西MyApp.Controllers.RecordsController.Index (MyApp)

我宁愿更喜欢这样的东西:

<script>$("li#@(Controller.Name)-@(Action.Name)")).addClass("active");</script>
Run Code Online (Sandbox Code Playgroud)

iti*_*omi 32

使用

var controller = ViewContext.RouteData.Values["Controller"];
var action = ViewContext.RouteData.Values["Action"];

<script>
$("li#@(ViewContext.RouteData.Values["Controller"])-@(ViewContext.RouteData.Values["Action"])")).addClass("active");
</script>
Run Code Online (Sandbox Code Playgroud)

PS:如果需要,使用ToLower()

ViewContext.RouteData.Values["Action"].ToString().ToLower();
Run Code Online (Sandbox Code Playgroud)

您也可以按样式块激活菜单

<style>
li#@(ViewContext.RouteData.Values["Controller"])-@(ViewContext.RouteData.Values["Action"]) {
//add some style
}
</style>
Run Code Online (Sandbox Code Playgroud)


小智 10

使用针对剃刀页面的dot net core 2.0,您可以像这样使用

var rv = ViewContext.RouteData.Values;
string page = $"{rv["page"]}".ToLowerInvariant();
Run Code Online (Sandbox Code Playgroud)

在标签上

<li class="@(page == "/index" ?  "active" : "")"><a asp-page="/Index" >Home</a></li>
Run Code Online (Sandbox Code Playgroud)


小智 5

我想添加一些可能被忽略的小东西......只需在顶部的布局页面中添加一些嵌入式代码,在 HTML 开始之前......

@{
    var controller = ViewContext.RouteData.Values["Controller"];
    var action = ViewContext.RouteData.Values["Action"];
}
Run Code Online (Sandbox Code Playgroud)

代码是不言自明的......然后从代码中的任何地方调用变量的值,就像我做的那样,如下所示:

<div class="navbar-wrapper">
<h3>@controller | @action</h3>
</div>
Run Code Online (Sandbox Code Playgroud)

我发现这种方法比上述方法简单得多。啦啦队 ;)