Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track the current active page, or how to get controller and action names in a view

Tags:

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> 
like image 938
serge Avatar asked Aug 03 '17 08:08

serge


People also ask

What are controllers and actions in MVC?

In ASP.NET MVC, a Controller is used to define and group a set of actions. An action (or action method ) is a method on a controller that handles incoming requests.

What is ControllerContext?

ControllerContext(HttpContextBase, RouteData, ControllerBase) Initializes a new instance of the ControllerContext class by using the specified HTTP context, URL route data, and controller.


2 Answers

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> 
like image 174
itikhomi Avatar answered Nov 24 '22 07:11

itikhomi


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> 
like image 25
Ravi Selvaraj Avatar answered Nov 24 '22 09:11

Ravi Selvaraj