使用ASP.NET MVC条件设置li元素类

时间:2017-01-23 17:59:17

标签: css asp.net-mvc razor menuitem

我在/Shared/MainMenu.cshtml中有一个简单的菜单:

  <ul class="nav navbar-nav">
    <li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
    <li>@Html.ActionLink("Features", "Index", "Features", "active")</li>
    <li>@Html.ActionLink("Faq", "Index", "Faq")</li>
    <li>@Html.ActionLink("Help", "Index", "Help")</li>
  </ul>

我想指出当前页面,但在Index.cshtml中设置一个值,并将相关

  • 元素的类设置为&#34; active&#34;,就像& #34;首页&#34;菜单项有,上面。

    设置相关

  • 的类而不设置其他类的最简单方法是什么?

  • 1 个答案:

    答案 0 :(得分:2)

    也许?

    @{
        String controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
    }
    
    <ul class="nav navbar-nav">
        <li class="@(controller == "Home" ? "active": "")">@Html.ActionLink("Home", "Index", "Home")</li>
        <li class="@(controller == "Features" ? "active": "")">@Html.ActionLink("Features", "Index", "Features", "active")</li>
        <li class="@(controller == "Faq" ? "active": "")">@Html.ActionLink("Faq", "Index", "Faq")</li>
        <li class="@(controller == "Help" ? "active": "")">@Html.ActionLink("Help", "Index", "Help")</li>
      </ul>