I have a web page with a navigation menu. The current page must be highlighted, which is done by adding a css class. But this menu is defined in the layout page, so how can I add the class to the current menu item?
The only solution I can think of is to use a unique ViewBag property for each menu item, and use that to add the class from the appropriate Action method.
Example:
<div class="link @ViewBag.DashboardActive">
@Html.ActionLink("Dashboard", "Index")
</div>
<div class="link @ViewBag.Item2Active">
@Html.ActionLink("Item2", "Item2")
</div>
etc.
This does the job, but I have a feeling that there is a more elegant way to solve this.
You could write a custom helper that will generate those menus and apply a CSS class to the currently selected item. You lay take a look at the following example. And here’s a similar which uses an anchor.