gpt4 book ai didi

c# - ASP.NET MVC : Render raw attribute value using TagBuilder

转载 作者:行者123 更新时间:2023-11-30 18:22:02 29 4
gpt4 key购买 nike

鉴于以下情况:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com