Set The Active Class On Bootstrap Nav Links In MVC

Here’s a quick way to set the active class on the current URL with a .Net MVC application.

1. Set a string variable equal to the request path at the top of the layout or view:

@{ 
    string path = Context.Request.Path;
}

2. Check the path variable against whatever the base url of the nav-link is. Add the “active” class if the path starts with your base path.

<a class="nav-link @(path.StartsWith("/robots") ? "active" : "")" href="/robots">Robots</a>

Now you will get the “active” highlight class on the correct nav-link when the current request matches the appropriate URL.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>