Track the current active page, or how to get contr

2020-06-01 07:03发布

I am new in ASP.NET Core. I have a navigation menu and I would like to track the active item. My idea is to use the action and controller names as navigation keys:

enter image description here

the problem is I don't know how to obtain the action and controller name in the _Layout.cshtml view...

I have tried the ViewContext.ActionDescriptor.DisplayName but it renders something like this MyApp.Controllers.RecordsController.Index (MyApp)

I'd rather prefer to obtain something like this:

<script>$("li#@(Controller.Name)-@(Action.Name)")).addClass("active");</script>

4条回答
成全新的幸福
2楼-- · 2020-06-01 07:31

You can achieve this server side if you combine this answer with the following.

Somewhere in your view.

@{
    var rv = ViewContext.RouteData.Values;
    var id = $"{rv["Controller"]}-{rv["Action"]}".ToLowerInvariant();
}

On each <li>.

<li class-conditional-active="@(id == "records-index")">...</li>
查看更多
Lonely孤独者°
3楼-- · 2020-06-01 07:36

Use

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>

PS: Use ToLower() if required

ViewContext.RouteData.Values["Action"].ToString().ToLower();

Also you can activate your menu by style block

<style>
li#@(ViewContext.RouteData.Values["Controller"])-@(ViewContext.RouteData.Values["Action"]) {
//add some style
}
</style>
查看更多
迷人小祖宗
4楼-- · 2020-06-01 07:37

I would like to add something small that has perhaps been overlooked... Just add some embedded code in the layouts page at the top, before the HTML begins...

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

The code is pretty self-explanatory... Then call the variables' values from anywhere within your code just as they are, like the way I did as shown below:

<div class="navbar-wrapper">
<h3>@controller | @action</h3>
</div>

I found this method to be much simpler and hassle-free than aforementioned methods. Cheerio ;)

查看更多
欢心
5楼-- · 2020-06-01 07:42

With dot net core 2.0 for razor pages you could use like this

var rv = ViewContext.RouteData.Values;
string page = $"{rv["page"]}".ToLowerInvariant();

On the tags

<li class="@(page == "/index" ?  "active" : "")"><a asp-page="/Index" >Home</a></li>
查看更多
登录 后发表回答