MVC 5 Razor主动导航选项卡

时间:2014-06-04 13:31:16

标签: c# css asp.net-mvc razor

我一直在尝试突出显示项目中的“活动导航”选项卡。我的任务是更新旧网站而不更改为bootstrap(这是我的经验)。我发现了一个拥有我需要的大部分内容的例子。现在是唯一具有"选定类"是主页选项卡。当我单击另一个选项卡时,“主页”选项卡不再突出显示,但当前选项卡不再突出显示。当我检查元素时,Home选项卡仍然具有"选择的类"属性。不知道该怎么办。

_layout

        <ul id="navigation">
            <li class="@Html.ActivePage("Home", "Index")">@Html.ActionLink("Home", "Index", "Home")</li>
            <li class="@Html.ActivePage("About", "About")">@Html.ActionLink("About", "About", "Home")</li>
            <li class="@Html.ActivePage("Products", "Products")">@Html.ActionLink("Products", "Products", "Home")</li>
            <li class="@Html.ActivePage("Services", "Services")">@Html.ActionLink("Services", "Services", "Home")</li>
            <li class="@Html.ActivePage("Contact", "Contact")">@Html.ActionLink("Contact", "Contact", "Home")</li>
        </ul>

HtmlHelper Class

public static class HtmlHelperExtensions
{
    public static string ActivePage(this HtmlHelper helper, string controller, string action)
    {
        string classValue = "";

        string currentController = helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
        string currentAction = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();

        if (currentController == controller && currentAction == action)
        {
            classValue = "selected";
        }

        return classValue;
    }
}

CSS

ul#navigation li {
    list-style: none;
    float: left;
    position: relative;
    background: url(../images/mi-standby.gif) no-repeat left top;
    padding-left: 3px;
    margin-left: 6px;
}

ul#navigation a {
    float: left;
    display: block;
    background: url(../images/mi-standby.gif) no-repeat right top;
    padding: 10px 29px 6px 26px;
    text-decoration: none;
    font-weight: bold;
    font-size: .8em;
    color: #a6a6a6;
}

ul#navigation li.selected a {
    background: url(../images/mi-active.gif) no-repeat right top;
    color: #FFF;
}

ul#navigation li.selected {
    background: url(../images/mi-active.gif) no-repeat left top;
    color: #FFF;
}

ul#navigation li a:active {
    background-color: #ff0000;
    text-decoration: none;
    color: #ffffff;
}

1 个答案:

答案 0 :(得分:5)

您的帮助器方法正在查看当前控制器和操作是否与您传入的值匹配,但是您将操作的名称作为两个参数传递。从您的代码段看起来,您的HomeController上的所有操作都是如此,因此请尝试使用以下内容替换您的视图:

    <ul id="navigation">
        <li class="@Html.ActivePage("Home", "Index")">@Html.ActionLink("Home", "Index", "Home")</li>
        <li class="@Html.ActivePage("Home", "About")">@Html.ActionLink("About", "About", "Home")</li>
        <li class="@Html.ActivePage("Home", "Products")">@Html.ActionLink("Products", "Products", "Home")</li>
        <li class="@Html.ActivePage("Home", "Services")">@Html.ActionLink("Services", "Services", "Home")</li>
        <li class="@Html.ActivePage("Home", "Contact")">@Html.ActionLink("Contact", "Contact", "Home")</li>
    </ul>