I am building a sidebar navigation dynamically and I have the following issue:
Option 1 // add class active
Option 1.1 // add class active
Option 1.1.1 // add class active
Option 1.1.1.1 // add class active
option 1.1.1.1.1 // selected link id = 7 (this is guid in real app)
Option 1.1.2
Option 1.2
Option 2
Option 3
Basically the navigation is in the following format:
<ul>
<li>
<a href="">link</a>
</li>
<li>
<a href="">link</a>
<ul>
<li>
<a href="">link</a>
</li>
</ul>
</li>
</ul>
And here is what I try to do recursively.
@BuildNavigation(Model)
@helper BuildNavigation(IEnumerable<Menu> menu)
{
foreach (Menu item in menu)
{
<li>
<a href="@Url.Action(item.Action, item.Controller, new { id = item.MenuId })" id="@item.MenuId">@item.Title</a>
@if (item.Items.Any())
{
<ul class="nav sub-menu">
@BuildNavigation(item.Items)
</ul>
}
</li>
}
}
This works fine, the sidebar is built. But how can I add the active classes to the <li>
based on the current selection?
I can add a property to the Menu
class bool IsActive
and then within the view I can check if that menu is active but how can I add the active class to all parents <li>
of that selected link?