将IHtmlContent / TagBuilder转换为C#中的字符串
我正在使用ASP.NET 5.我需要将IHtmlContent转换为String
IIHtmlContent
是ASP.NET 5
Microsoft.AspNet.Html.Abstractions
命名空间的一部分,是TagBuilder
实现的接口
简化我有以下方法
public static IHtmlContent GetContent() { return new HtmlString("blah"); }
当我参考它
string output = GetContent().ToString();
我得到GetContent()的以下输出
"Microsoft.AspNet.Mvc.Rendering.TagBuilder"
并不是
blah
我想要的
我也尝试过使用StringBuilder
StringBuilder html = new StringBuilder(); html.Append(GetContent());
但它也会附加相同的命名空间而不是字符串值
我试着把它投射到TagBuilder
TagBuilder content = (TagBuilder)GetContent();
但TagBuilder没有转换为字符串的方法
如何将IHtmlContent或TagBuilder转换为字符串?
如果您只需将内容输出为字符串,只需添加此方法并将您的IHtmlContent对象作为参数传递以获取字符串输出:
public static string GetString(IHtmlContent content) { var writer = new System.IO.StringWriter(); content.WriteTo(writer, new HtmlEncoder()); return writer.ToString(); }
您可能想重新考虑为什么采用这种方法,因为TagBuilder允许您可以想到的任何类型的自定义HTML。 手动输出文本可能不是必需的。
加上上面的答案:
HtmlEncoder
的新实例在ASP.NET Core RTM中不起作用,因为Microsoft.Extensions.WebEncoders
命名空间被删除,新的HtmlEncoder
类被移动到新的命名空间System.Text.Encodings.Web
,但此类现在是写为抽象和密封类,因此您无法从中创建新实例或派生类。
将HtmlEncoder.Default
传递给方法,它将工作
public static string GetString(IHtmlContent content) { var writer = new System.IO.StringWriter(); content.WriteTo(writer, HtmlEncoder.Default); return writer.ToString(); }
ASP.NET Core实际上引入了一些谨慎的优化。 如果要构建HTML扩展方法,那么最有效的方法是避免使用字符串:
public static IHtmlContent GetContent(this IHtmlHelper helper) { var content = new HtmlContentBuilder() .AppendHtml("- ") .AppendHtml(helper.ActionLink("Home", "Index", "Home")) .AppendHtml("
"); if(SomeCondition()) { content.AppendHtml(@" Note `HtmlContentBuilder.AppendHtml()` is Mutable as well as Fluent/Chainable. "); } return content; }
最后在剃刀视图中,我们甚至不再需要@Html.Raw(Html.GetContent())
(以前在ASP.NET MVC 5中需要),只需调用@Html.GetContent()
就足够了Razor将照顾所有逃脱的业务。
上述就是C#学习教程:将IHtmlContent / TagBuilder转换为C#中的字符串分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1021400.html