MVC5 - Navbar活动颜色

时间:2017-02-05 19:53:28

标签: css asp.net-mvc twitter-bootstrap asp.net-mvc-5

当我点击它并转到该视图时,我无法在导航栏中获取活动li来改变颜色,我在下面列出了一些代码但是如果需要我会向您展示更多

这是我的布局共享视图中的导航栏代码:

<header id="main-header">
    <div class="container">
        <a href="@Url.Action("Index", "Home")">
            <img src="~/logo.png" id="logo" alt="logo" />
        </a>
        <nav class="main-nav">
            <ul>
                @if (User.IsInRole("Admin"))
                {
                    <li>@Html.ActionLink("Venues", "Index", "Venues")</li>
                    <li>@Html.ActionLink("Events", "Index", "Events")</li>
                    <li>@Html.ActionLink("Bands", "Index", "Bands")</li>
                    <li>@Html.ActionLink("Admin", "Admin", "Home")</li>
                    @Html.Partial("_LoginPartial")
                }
                else
                {
                    <li>@Html.ActionLink("Venues", "Index", "Venues")</li>
                    <li>@Html.ActionLink("Events", "Index", "Events")</li>
                    <li>@Html.ActionLink("Bands", "Index", "Bands")</li>
                    <li>@Html.Partial("_LoginPartial")</li>
                }
            </ul>
        </nav>
    </div>
</header>

这是我的Header-Nav css课程:

.main-nav {
    float: right;
    padding-top: 17px;
}
.main-nav li {
    float: left;
    list-style: none;
    margin-right: 10px;
    position: relative;
}
.main-nav li:last-child {
    margin-right: 0px;
}
.main-nav li.current > a {
    border: 1px solid;
}
.main-nav li a {
    text-transform: uppercase;
    font-size: 15px;
    color: #fff;
    font-weight: 400;
    padding: 2px 10px;
    font-family: 'Montserrat', sans-serif;
}

1 个答案:

答案 0 :(得分:2)

在所需控制器的每个操作方法中,您可以添加ViewBag值:

public ActionResult Index()
{
    ViewBag.Action = ControllerContext.RouteData.Values["Action"].ToString();
    ViewBag.Controller = ControllerContext.RouteData.Values["Controller"].ToString();

    return View();
}

然后在视图中,您可以使用以下内容来应用所需的CSS类:

<li class="@(ViewBag.Action == "Index" && ViewBag.Controller == "Venues" ? "current" : "")">@Html.ActionLink("Venues", "Index", "Venues")</li>
<li class="@(ViewBag.Action == "Index" && ViewBag.Controller == "Events" ? "current" : "")">@Html.ActionLink("Events", "Index", "Events")</li>
<li class="@(ViewBag.Action == "Index" && ViewBag.Controller == "Bands" ? "current" : "")">@Html.ActionLink("Bands", "Index", "Bands")</li>
<li class="@(ViewBag.Action == "Admin" && ViewBag.Controller == "Home" ? "current" : "")">@Html.ActionLink("Admin", "Admin", "Home")</li>

这可能是这些简单链接的正常解决方案 - 但如果您要添加更多链接,我建议您添加自己的自定义HtmlHelper。有关详细信息,请参阅此处接受的答案:How to add "active" class to Html.ActionLink in ASP.NET MVC

修改

你可以在控制器中使用它来简化它:

public class EventsController : Controller
{
    public ActionResult Index()
    {
        ViewBag.LinkText = "Events";

        return View();
    }
}

然后链接就是,例如:

<li class="@(ViewBag.Linktext == "Events" ? "current" : "")">@Html.ActionLink("Events", "Index", "Events")</li>