本文介绍了转换IHtmlContent / TagBuilder字符串在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET 5.我需要IHtmlContent转换为字符串

I am using ASP.NET 5. I need to convert IHtmlContent to String

IIHtmlContent ASP.NET 5 Microsoft.AspNet.Html的一部分。抽象命名空间,是一个接口, TagBuilder 工具

IIHtmlContent is part of the ASP.NET 5 Microsoft.AspNet.Html.Abstractions namespace and is an interface that TagBuilder implements

简体我有以下方法

public static IHtmlContent GetContent()
{
    return new HtmlString("<tag>blah</tag>");
}

当我引用它

string output = GetContent().ToString();

我得到的getContent以下输出()

I get the following output for GetContent()

"Microsoft.AspNet.Mvc.Rendering.TagBuilder" 

而不是

<tag>blah</tag>

我想

我使用StringBuilder的也试过

I also tried using StringBuilder

StringBuilder html = new StringBuilder();
html.Append(GetContent());

但它也追加了相同的命名空间,而不是字符串值

but it also appends the same namespace and not the string value

我试图将其转换为TagBuilder

I tried to cast it to TagBuilder

TagBuilder content = (TagBuilder)GetContent();

但TagBuilder不具有转换为字符串的方法

but TagBuilder doesn't have a method that converts to string

我如何转换IHtmlContent或TagBuilder为一个字符串?

How do I convert IHtmlContent or TagBuilder to a string?

推荐答案

如果你需要做的是输出的内容作为一个字符串,只需添加此方法并传入你的IHtmlContent对象作为参数,以获得字符串输出:

If all you need to do is output the contents as a string, just add this method and pass your IHtmlContent object as a parameter to get the string output:

public static string GetString(IHtmlContent content)
{
    var writer = new System.IO.StringWriter();
    content.WriteTo(writer, new HtmlEncoder());
    return writer.ToString();
}

您可能要重新考虑你为什么要采取这种方法的TagBuilder允许几乎任何类型的你能想到的自定义HTML的。输出文本手动大概是没有必要的。

You may want to reconsider why you're taking this approach as the TagBuilder allows for just about any type of custom HTML you can think of. Outputting the text manually probably isn't necessary.

这篇关于转换IHtmlContent / TagBuilder字符串在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:18