Set menu item to Active in MVC with BootStrap

Recent I start working on MVC with BootStrap for building the great Web UI. I am building a menu with several menu items and found out that it is not setting as “active” in the class of the item when a page is loaded.

BootStrap_menu_01

By default the MVC template doesn’t add the active class to the “li” item in the menu. So I have to add the class=”active” to the “li” to indicate the active menu item.

BootStrap_menu_02

Above is the code that is used for the actual menu that create the menu in the first screenshot. if you look at line 8, you will see the class=”active”, this is what makes the active menu item. In order for us to do this, we need to know what page is currently loaded and then apply the active class css to the corresponding “li” element. The best way to do this, is to create a HTML helper to handle this for us.

Now, let’s try to create a new folder in the project and called “Helpers”. Then add a new class named “HtmlHelpers.cs” (from my sample, I used KenLinHtmlHelpers). here we could create an extension method of the HtmlHelpers method. We do this by creating a static class.

BootStrap_menu_03

As you can see, I have created 2 method, IsActive and IsActiveController. The only difference is, do you want to take Action into one of the input parameter. If you want to set class is active whenever it is in the specific controller, you could use IsActiveController. Otherwise, you may use IsActive if you want the active class only in exactly the specified Action and Controller. Please also note that, I am letting the activeClass and inActiveClass input as optional with a default value.

Now we could update our cshtml as below,

BootStrap_menu_04

Look carefully on each “li” item now. There is a new HtmlHelper method to check and show if it is the active controller.  Please also look carefully, I have also called the method in line 9, for the parents of the dropdown Menu.

NOTE: You have to reference the class in the top of the view page that you are using the IsActive or IsActiveController method in. Just add the code as line 1 of the above screenshot.