sushiBite
sushiBite

Reputation: 361

selected tab in a menu

I'm wondering about how I can have selected tabs in mvc3 razor

my menu code is ->

<ul id="iecMenu" class="zeroPadding">
   <li id="menuHome">@Html.ActionLink("Home","Index", "Home")</li>
   <li id="menuOverView">@Html.ActionLink("OverView","Trips", "Trip")</li>
   <li id="menuParse">@Html.ActionLink("Parse", "Create", "Day")</li>
   <li id="menuSettings">@Html.ActionLink("Settings", "Index", "Settings")</li>
</ul>

Is there a simple way to have one of those tabs selected, ps. there are sub pages as well but I only want one these Items to be selected.

Thanks sushiBite

Upvotes: 0

Views: 609

Answers (2)

sushiBite
sushiBite

Reputation: 361

I ended up using the ViewBag to create a small script. So in each controller I created an constructor

public CurrencyFilterController()
{
    ViewBag.MenuItemScript = helper.createMenuItemScript("menuSettings");
}

The CreateMenuItemScript method ->

public string createMenuItemScript(string menuItem)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("<script type=\"text/javascript\">");
    sb.AppendLine("$(document).ready(function () {");
    sb.AppendLine("$(\"#" + menuItem + "\").addClass(\"selected\")");
    sb.AppendLine("});");
    sb.AppendLine("</script>");
    return sb.ToString();
}

Then in my _Layout.cshtml

@Html.Raw(ViewBag.MenuItemScript)

This works like a charm :)

Hope it helps someone

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

I'd guess you have a class you'd apply to the li to show a selecetd menu item and this is in your master page. The usual way to pass this along is through the ViewBag or ViewData. You can pass it from the Action

ViewBag.MenuItem = "menuHome";

and then the master page would read

<li id="menuHome" @ViewBag.MenuItem == "menuHome"? "class=\"selected"\"":"">@Html.ActionLink("Home","Index", "Home")</li>

Or you can get fancy and place it into an attribute (which inherits from the ActionFilterAttribute, which you could apply over both actions and controllers. Something else to consider is to make the menu choices into an enumeration, to have your code more strongly typed and not comparing strings.

Upvotes: 1

Related Questions