【问题标题】:Adding a class to Html.MenuItem's向 Html.MenuItem 添加一个类
【发布时间】:2012-02-02 19:26:01
【问题描述】:

我有一个由 MVC 2 生成的菜单项的 HTML 列表。

<%= Html.MenuItem("Home", "Home", "Index")%>
<%= Html.MenuItem("Login", "Login", "Account")%>

在 HTML 中生成:

<li>
  <a href="Index">Home</a>
</li>

<li>
  <a href="Account">Login</a>
</li>

如何为列表中的每个项目向列表中的元素添加 CSS 类?

【问题讨论】:

    标签: model-view-controller asp.net-mvc-2 asp.net-mvc


    【解决方案1】:

    我猜这个 MenuItem 是您编写的或从某人那里获取的扩展方法,我也猜他们正在包装一个 ActionLink 方法,如:

    public static string MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName)
    {
        string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
        string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
    
        // Add selected class
        if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
            return string.Concat("<li class=\"selected\">", helper.ActionLink(linkText, actionName, controllerName), "</li>");
    
        // Add link
        return string.Concat("<li>", helper.ActionLink(linkText, actionName, controllerName), "</li>");
    }
    

    如果是这种情况,只需将 css 类作为参数,并使用接收 html 属性的 ActionLink,如下所示:

    public static string MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName, string cssClass = "menu-item")
    {
        string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
        string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
    
        // Add selected class
        if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
            return string.Concat("<li class=\"selected\">", helper.ActionLink(linkText, actionName, controllerName), "</li>");
    
        // Add link
        return string.Concat("<li>", helper.ActionLink(linkText, actionName, controllerName, new {@class = cssClass} ), "</li>");
    }
    

    那么你就这样称呼他们:

    <%= Html.MenuItem("Home", "Home", "Index", "index-tem")%>
    

    【讨论】:

      猜你喜欢
      • 2011-12-03
      • 1970-01-01
      • 2020-05-11
      • 2016-05-16
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多