zsharp
zsharp

Reputation: 13756

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?

Upvotes: 8

Views: 10687

Answers (4)

tvanfosson
tvanfosson

Reputation: 532465

If you can live with a javascript solution, look at how the jQuery UI Accordion plugin handles this. Essentially, you can choose the highlighted tab based on the controller by examining the request url when the page is loaded.

Alternatively, you can set a ViewBag item for each tab that corresponds to the tab's class value. Set the value for the current tab to the active css class and the others to empty (or their defaults). Then you can use:

<li id="HomeTab" class="<%= ViewBag.HomeTabClass %>" />
<li id="OtherTab" class="<%= (string)ViewBag.OtherTabClass %>" />

In your controller, you would then set up the proper values for the ViewData variables.

ViewBag.HomeTabClass = "tab activeTab";
ViewBag.OtherTabClass = "tab";

Upvotes: 3

Carl Weis
Carl Weis

Reputation: 7062

I've tried to get this to work with no luck.

What's your CSS look like? Mine is below.

.activeTab { background:#FFFFFF; color:#000000; }

I'm using this with the master page and not the home view, not sure if that's affecting it.

Upvotes: 1

Geo
Geo

Reputation: 8761

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>

Upvotes: 5

Zhaph - Ben Duguid
Zhaph - Ben Duguid

Reputation: 26956

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?

Upvotes: 4

Related Questions