0

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?

user2818430
  • 5,853
  • 21
  • 82
  • 148
  • Possibly a little jquery would do the trick. http://stackoverflow.com/questions/5873885/how-to-addclass-for-all-parent-of-an-element-using-jquery – Steve Greene Aug 13 '15 at 17:12
  • Check this link out, http://stackoverflow.com/questions/20410623/how-to-add-active-class-to-html-actionlink-in-asp-net-mvc – pool pro Aug 13 '15 at 17:22

0 Answers0