Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc and css: Having menu tab stay highlighted on selection

Is there a better way to do this?

I have an HTML helper extension method that checks if the current tab menu is the the selected one and then chooses .selected css class or not. I put the html.IsSelected link in each li as

<li class="<%=Html.IsSelected(string a, string b)%>" >

where a is the tab name and b is ViewData assigned.

is this clean or is there a better way?

like image 617
zsharp Avatar asked Jan 24 '09 01:01

zsharp


2 Answers

This approach I am using in one of my projects and is working pretty well. I assigned in each controller ViewData["Home"] = "activeTab" class, and use in the view a default value of empty string, as showing below. This will make the tab active if the value of that viewData dictionary is taken. Is simple and very clean.

Your home controller will look like this:

        ViewData["Home"] = "activeTab";

        return View("Index");
    }

The view will look like this:

<li class="<%= ((string)ViewData["Home"] ?? "") %>"><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li class="<%= ((string)ViewData["About"] ?? "") %>"><%= Html.ActionLink("About", "About", "Home")%></li>
like image 121
Geo Avatar answered Sep 18 '22 18:09

Geo


You could also take a look at a previous suggestion:

An easy way to set the active tab using controllers and a user control in ASP.NET MVC?

like image 22
Zhaph - Ben Duguid Avatar answered Sep 18 '22 18:09

Zhaph - Ben Duguid