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:
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>
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.
ControllerContext(HttpContextBase, RouteData, ControllerBase) Initializes a new instance of the ControllerContext class by using the specified HTTP context, URL route data, and controller.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With