【问题标题】:Edit the innerhtml of a <li> to add an <i> tag with icon image编辑 <li> 的 innerhtml 以添加带有图标图像的 <i> 标记
【发布时间】:2013-08-27 09:12:11
【问题描述】:

我已经创建了一个自定义助手来跟踪我的 MVC 应用程序中的当前菜单项,现在我想替换我在更改之前使用的图标并设置相关的 href。以前我的列表项如下所示:

<li><a href="@Url.Action("Index", "Admin")"><i class="icon-lock"></i>Admin</a></li>            
<li><a class="active" href="@Url.Action("Index", "Home")"><i class="icon-home"></i>Home</a></li>

我现在使用以下代码创建了通用菜单项:

using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MetaLearning.Helpers
{
  public static class MenuExtensions
  {
    public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper,
                                         string text, string action,
                                         string controller,
                                         string iconClass,
                                         object routeValues = null,
                                         object htmlAttributes = null)
    {
        var li = new TagBuilder("li");
        var routeData = htmlHelper.ViewContext.RouteData;
        var currentAction = routeData.GetRequiredString("action");
        var currentController = routeData.GetRequiredString("controller");
        li.InnerHtml = @"<a class=""active"" href=""/""><i class=""icon-home""></i>Home</a>";
        if (currentController.Contains(text))
        {
            li.InnerHtml = @"<a class=""active"" href=""/""><i class=""icon-home""></i>"+ text + "</a>";
        }
        else
        {
            li.InnerHtml = @"<a href=""/""><i class=""icon-home""></i>" + text + "</a>";
        }

        return MvcHtmlString.Create(li.ToString());
    }
  }
}

如何将 href 设置为“/controller”并将图标的名称设置为 iconClass。我尝试了以下方法:

li.InnerHtml = @"<a class=""active"" href=""/""><i class=""icon-home""></i>"+ text + "</a>";

这样我成功地显示了正确的文本,但是当我尝试用相关变量替换 href 或图标类名称时,我的字符串格式不正确

【问题讨论】:

    标签: css asp.net-mvc controller innerhtml


    【解决方案1】:

    尝试 not 将字符串与 '+' 运算符连接这是不好的行为here 你可以自己阅读更多内容。

    如何将 href 设置为“/controller”和图标的名称 到 iconClass。

     li.InnerHtml = string.Format("<a href=\"{0}\"><i class=\"{2}\" /i>{1}</a>", controller, iconClass, text);
    

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 2022-09-27
      • 2014-04-23
      相关资源
      最近更新 更多