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.