鉴于以下情况:
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());
最佳答案
试试这个小助手扩展
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>
关于c# - ASP.NET MVC : Render raw attribute value using TagBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541190/