1

我正在开发一个 MVC4 应用程序

我有以下菜单项

<ul class="menu left">
                <li>@Html.ActionLink("Home", "Index", new { Controller = "Home" }, new { @class = "active" })</li>
                <li>@Html.ActionLink("About Us", "About", new { Controller = "Home" })</li>
                <li>@Html.ActionLink("Services", "Services", new { Controller = "Home" })</li>      
                <li>@Html.ActionLink("Post Job", "Create", new { Controller = "JobPosting" })</li>
                <li>@Html.ActionLink("Job Search", "Index", new { Controller = "JobPosting" })</li>
                <li>@Html.ActionLink("Contact Us", "Contact", new { Controller = "Home" })</li>
           </ul>

现在我想如果我点击 Home 以外的项目,它的 css 类会变为活动状态。基本上我只想改变菜单项的颜色我怎样才能动态地做到这一点?

4

2 回答 2

3

如果您想根据 Action 或 Controller 更改 css,您可以使用

@{
    var controller = ViewContext.RouteData.Values["Controller"].ToString();
    var action = ViewContext.RouteData.Values["Action"].ToString();
}

<li> 
    @if (action == "Home") { 
       @Html.ActionLink("Home", "Index", new { Controller = "Home" },new {@class="active" })
    }
    else {
       @Html.ActionLink("Home", "Index", new { Controller = "Home" })
    }
</li>
<li>
   @if (action == "About Us") { 
           @Html.ActionLink("About Us", "About", new { Controller = "Home" },new {@class="active" })
        }
        else {
           @Html.ActionLink("About Us", "About", new { Controller = "Home" })
        }
</li>

ETC...

于 2013-02-08T11:28:26.877 回答
0
public static class MyHtmlHelper
{
    public static String NavActive(this HtmlHelper htmlHelper, 
                          string actionName, 
                          string controllerName)
    {
        var controller = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
        var action = htmlHelper.ViewContext.RouteData.GetRequiredString("action");

        if (controllerName == controller && action == actionName )
            return "active";
        else
            return String.Empty;
    }
}

然后你可以在你的视图中使用这个助手。

@Html.NavActive("Index", "Home")

例如,

<li>
    <a href="~/Home/Index" class="@Html.NavActive("Index", "Home")">
        <span>Index</span>
    </a>
</li>
于 2013-02-08T11:38:52.737 回答