views:

132

answers:

2

I've seen this question, An easy way to set the active tab , however I'm not sure this is an optimal solution.

I'm looking to see how others have handled tab selection in their views/controllers in ASP.NET MVC.

What is the simplest way to implement selectable tabs in ASP.NET MVC? I'd like to avoid javascript methods to allow for non-js enabled browsers to still see the selected tab.

A: 

EDIT: Scratch that above, that's not what I did, that was a non-working combination of two methods I used.

I've had to handle on states in two different places on one page. The first way I just added CSS to the view to change the tab to the correct style. The second thing I had to do was use ViewData to give me a variable that I passed to a helper I wrote to output CSS in the head section of the view to indicate a page-specific on state (if that makes sense, kind of like a category would be highlighted on a page of products).

So in my view I have these twho lines:

<% var onState = ViewData["OnState"].ToString(); %>
<%= Html.OutputOnState(onState) %>

That accomplishes what I'm after very well. The CSS is hard-coded into the helper since this is a small site, so I'm sure there is a better way to do this.

dhulk
A: 

I do something similar to the following over simplified example ;-)

Controller:

public ActionResult Index()
{
    ViewData["MainMenuOn"] = "Home";
    return View();
}

public ActionResult About()
{
    ViewData["MainMenuOn"] = "About";
    return View();
}

public ActionResult Contact()
{
    ViewData["MainMenuOn"] = "Contact";
    return View();
}

View:

<ul id="main-menu">
    <li class="<%= Html.MainMenuOn("Home") %>">... action link for home action ...</li>
    <li class="<%= Html.MainMenuOn("About") %>">... action link for about action ...</li>
    <li class="<%= Html.MainMenuOn("Contact") %>">... action link for contact action ...</li>
</ul>

Helper extension:

public static string MainMenuOn(this HtmlHelper html, string menuItem)
{
    if ((html.ViewData["MainMenuOn"] != null) && (html.ViewData["MainMenuOn"] == menuItem))
        return "on";

    return "";
}

Then your css should be rather simple

ul#main-menu li
{
    background: green;
}

ul#main-menu li.on
{
    background: blue;
}

There are many ways to skin this cat... depending on your needs I would start looking at different ways to implement the HtmlHelper extension.

HTHs, Charles

Charlino