Change li class depending on current webpage in MVC

I have an MVC application with a page _Layout

that assembles a main navbar.

For each li class, there is a special class needed to highlight the current page.

 <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-parent-item current-menu-item page_item current_page_item">
  @Html.ActionLink("Home", "index", "Home")<i class="fa fa-home hidden-xs"></i>
 </li>

      

How can I add this to other li classes when on this current page by removing it from Home

when viewed from it.

+3


source to share


1 answer


One way to accomplish this is to extract the URL from window.location.href

, extract the corresponding portion of the URL using a regular expression, then figure out how this relates to the corresponding navigation button, and give that button a class to highlight it - for example:

.current-page {
    background-color: yellow;
}

      



A simpler solution would be to simply add this class (or whatever) to the nav links on each individual view - something like this:

// <li id="about-me-section" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-parent-item current-menu-item page_item current_page_item">

$("#about-me-section").toggleClass("current-page");
$("#home-section").toggleClass("current-page");

      

+1


source







All Articles