0

我遇到了一个奇怪的错误。我的 html 助手应该为菜单、简单的 ul 和 li 呈现 html。现在问题变成了它开始在其他元素周围呈现标签。从 html 返回的字符串是正确的,之后似乎是什么导致了问题。我只是想不通为什么。所以我想也许一双新鲜的眼睛可以发现它。

方法

public static MvcHtmlString TopMenuLinks(this HtmlHelper helper, List<IMenuItemNodeViewData> menuItem)
        {
            if (menuItem != null && menuItem.Count > 0)
            {
                var count = 0;
                var resultString = "";

                var ulTag = new TagBuilder("ul");

                foreach (var item in menuItem.Where(x => x.IsVisibleInMenu))
                {
                    count++;
                    var liTag = new TagBuilder("li")
                                    {
                                        InnerHtml = string.Format("<a href=\"{0}\"><img src=\"{1}\" alt=\"{1}\" />{2}", item.URL, "/Content/images/image.png", item.Name)
                                    };

                    ulTag.InnerHtml += liTag.ToString();

                    if (count % 3 == 0 || count == menuItem.Where(x => x.IsVisibleInMenu).Count())
                    {
                        resultString += ulTag.ToString(TagRenderMode.Normal);
                        ulTag = new TagBuilder("ul");
                    }
                }

                return MvcHtmlString.Create(resultString);
            }

            return null;
        }

局部视图

<div class="top-columns link-container">

        <div class="links">

            <%= Html.TopMenuLinks(Model.MenuItems) %>

        </div>

    </div>

    <div class="top-columns icons">

        <div class="icons-contain">
            <img src="/Content/images/image.png" alt="image" />
        </div>

    </div>

它呈现以下内容

<div class="links">
    <ul>
        <li>..</li>
        <li>..</li>
        <li>..</li>
    </ul>
    <ul>
        <li>..</li>
        <li>..</li>
    </ul>
    <a href="url"></a>
</div>

<a href="url"></a>
</div>
<a href="url">

    <div class="top-columns icons">

        <div class="icons-contain">
        </div>

</a>
</div>
<a href="url"></a>

应该是

<div class="links">
    <ul>
        <li>..</li>
        <li>..</li>
        <li>..</li>
    </ul>
    <ul>
        <li>..</li>
        <li>..</li>
    </ul>
</div>
<div class="top-columns icons">

        <div class="icons-contain">
        </div>
</div>
4

1 回答 1

0

您忘记<a>在以下行中关闭标签:

  InnerHtml = string.Format("<a href=\"{0}\"><img src=\"{1}\" alt=\"{1}\" />{2}", item.URL, "/Content/images/image.png", item.Name)

试试这个 :

 InnerHtml = string.Format("<a href=\"{0}\"><img src=\"{1}\" alt=\"{1}\" />{2} </a>", item.URL, "/Content/images/image.png", item.Name)
于 2012-11-14T09:29:35.320 回答