ASP.NET MVC:使用TagBuilder

时间:2015-12-31 04:51:22

标签: c# asp.net asp.net-mvc

鉴于以下内容:

public MvcHtmlString CreateHtml(HtmlHelper helper)
{
    return MvcHtmlString.Create(CreateInnerHtml());
}

public string CreateSomeInnerHtml()
{
    var li = new TagBuilder("li");
    var a = new TagBuilder("a");
    a.Attributes["href"] = "http://test:8080/${{var}}";
    li.InnerHtml += a;
    return li.ToString(TagRenderMode.Normal);
}

如何以原始格式呈现href值?

我试过了

li.InnerHtml += htmlHelper.Raw(a);

而且,首先尝试对它进行解码......但是值得一试。

a.Attributes["href"] = WebUtility.UrlDecode("http://test:8080/${{var}}");

而且,这真的应该在没有编码的情况下呈现整个事物......

return MvcHtmlString.Create(helper.Raw(CreateInnerHtml())).ToHtmlString());

1 个答案:

答案 0 :(得分:0)

试试这个小助手扩展

public static class HtmlHelperExtensions {

    internal static IHtmlString ToHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode) {
        System.Diagnostics.Debug.Assert(tagBuilder != null);
        return new HtmlString(tagBuilder.ToString(renderMode));
    }

    public static IHtmlString CreateHtml(this HtmlHelper htmlHelper) {
         return CreateSomeInnerHtml();
    }

    public static IHtmlString CreateSomeInnerHtml() {
        var li = new TagBuilder("li");
        var a = new TagBuilder("a");
        a.Attributes["href"] = "http://test:8080/${{var}}";
        li.InnerHtml += a;
        return li.ToHtmlString(TagRenderMode.Normal); // Note the use of the extenson here
    }
}

并像

一样使用它
<div>
    <ul>
        @Html.CreateHtml()
    </ul>
</div>

呈现

<div>
    <ul>
        <li><a href="http://test:8080/${{var}}"></a></li>
    </ul>
</div>