Convert IHtmlContent/TagBuilder to string in C#

.net core tagbuilder example
c# html string
asp net core html helpers
htmlstring
tagbuilder in mvc
tagbuilder div
tagbuilder mobile
htmlstring net core example

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

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

Simplified I have the following method

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

When I reference it

string output = GetContent().ToString();

I get the following output for GetContent()

"Microsoft.AspNet.Mvc.Rendering.TagBuilder" 

and not

<tag>blah</tag>

which I want

I also tried using StringBuilder

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

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

I tried to cast it to TagBuilder

TagBuilder content = (TagBuilder)GetContent();

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

How do I convert IHtmlContent or TagBuilder to a string?

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)
{
    using (var writer = new System.IO.StringWriter())
    {        
        content.WriteTo(writer, HtmlEncoder.Default);
        return writer.ToString();
    } 
}     

Request, We have an extension method: public static string GetString(this IHtmlContent content) { var writer = new System.IO.StringWriter(); content. If by convert a string to tagbuilder you mean taking the entire html string and creating an instance of Tagbuilder, then you can't. However you can pass the tag name as an argument if you want. I believe link might be of interest to you.

Adding to the answer above:

The new instance of the HtmlEncoder doesn't work in ASP.NET Core RTM as the Microsoft.Extensions.WebEncoders namespace was removed and the new HtmlEncoder class is moved to a new namespace System.Text.Encodings.Web, but this class is now written as an abstract and sealed class so you can't create a new instance or a derived class from it.

Pass HtmlEncoder.Default to the method and it will work

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

Convert IHtmlContent/TagBuilder to string in C# - c#, I am using ASP.NET 5. I need to convert IHtmlContent to String IIHtmlContent is part of the ASP.NET 5 Microsoft.AspNet.Html.Abstractions namespace and is an  I am using ASP.NET 5. I need to convert IHtmlContent to String. IIHtmlContent is part of the ASP.NET 5 Microsoft.AspNet.Html.Abstractions namespace and is an interface that TagBuilder implements. Simplified I have the following method. public static IHtmlContent GetContent {return new HtmlString ("<tag>blah</tag>");} When I reference it

ASP.NET Core actually introduced handful of careful optimizations. If you are building an HTML extension method, then the most efficient way is to avoid string:

public static IHtmlContent GetContent(this IHtmlHelper helper)
{
    var content = new HtmlContentBuilder()
                     .AppendHtml("<ol class='content-body'><li>")
                     .AppendHtml(helper.ActionLink("Home", "Index", "Home"))
                     .AppendHtml("</li>");

    if(SomeCondition())
    {
        content.AppendHtml(@"<div>
            Note `HtmlContentBuilder.AppendHtml()` is Mutable
            as well as Fluent/Chainable.
        </div>");
    }

    return content;
}

Finally in the razor view, we don't even need @Html.Raw(Html.GetContent()) anymore (which used to be required in ASP.NET MVC 5) - not valid based on Lukáš Kmoch comment below: ASP.NET MVC 5 has type MvcHtmlString. You don't need to use Html.Raw()

just calling @Html.GetContent() is sufficient and Razor will take care of all the escaping business.

Convert IHtmlContent/TagBuilder to string in C#, I am using ASP.NET 5. I need to convert IHtmlContent to String IIHtmlContent is part of the ASP.NET 5 Microsoft.AspNet.Html.Abstractions namespace and is an  CreateSanitizedId(String, String) Returns a valid HTML 4.01 "id" attribute value for an element with the given name. GenerateId(String, String) Adds a valid HTML 4.01 "id" attribute for an element with the given name. Does nothing if Attributes already contains an "id" attribute or the name is null or empty. MergeAttribute(String, String)

there is a sample: https://github.com/aspnet/Mvc/blob/release/2.2/test/Microsoft.AspNetCore.Mvc.Views.TestCommon/HtmlContentUtilities.cs

public static string HtmlContentToString(IHtmlContent content, HtmlEncoder encoder = null)
        {
            if (encoder == null)
            {
                encoder = new HtmlTestEncoder();
            }

            using (var writer = new StringWriter())
            {
                content.WriteTo(writer, encoder);
                return writer.ToString();
            }
        }

c#, Estou usando o ASP.NET 5. Eu preciso converter IHtmlContent para StringIIHtmlContent faz parte do namespace ASP.NET 5 Microsoft.AspNet. C# (CSharp) TagBuilder - 30 examples found. These are the top rated real world C# (CSharp) examples of TagBuilder extracted from open source projects. You can rate examples to help us improve the quality of examples.

IHtmlContent Interface (Microsoft.AspNetCore.Html), C# Copy. public interface IHtmlContent Microsoft.AspNetCore.Html.​HtmlFormattableString · Microsoft.AspNetCore.Html.HtmlString TagBuilder · Microsoft. Notice, furthermore, how the TagBuilder.MergeAttributes() method is used to add a collection of attributes to the TagBuilder. The MergeAttributes() method accepts a Dictionary<string,object> parameter. The RouteValueDictionary class is used to convert the Object representing the collection of attributes into a Dictionary<string,object>.

‍ Convert IHtmlContent / TagBuilder to String in C #, If you only need to output the contents as a string, just add this method and pass the IHtmlContent object as a parameter to get the output of the  C# (CSharp) TagBuilder.WriteTo - 12 examples found.These are the top rated real world C# (CSharp) examples of TagBuilder.WriteTo extracted from open source projects. You can rate examples to help us improve the quality of examples.

What is the opposite? How do I convert reverse, a String to a TagBuilder ? Looking for a solution. Convert IHtmlContent/TagBuilder to string in C# public static  Notice, furthermore, how the TagBuilder.MergeAttributes() method is used to add a collection of attributes to the TagBuilder. The MergeAttributes() method accepts a Dictionary<string,object> parameter. The RouteValueDictionary class is used to convert the Object representing the collection of attributes into a Dictionary<string,object>.

Comments
  • What about ToHtmlString? Also, where do you get IHtmlContent from?
  • I was referring to HtmlString class's method. Can you point me to the documentation for IHtmlContent? It doesn't seem to be on MSDN
  • Good answer.. This is what I was looking for.
  • Does not work on asp.vnext core. use HtmlEncoder.Default instead
  • Shouldn't the StringWriter be wrapped in a using block?
  • @bradlis7 you are correct. I have updated the solution to reflect your suggestion.
  • With Razor in Core you can simply use @tagBuilderInstance. It will build and write the result.
  • The reason I liked the server side rendering is that it was so much faster to code boring markup at the expense of performance. Why are we injecting an ordered list into markup so we can render and anchor tag? This has to be bad for SEO, and increase development time. Arrrgh
  • ASP.NET MVC 5 has type MvcHtmlString. You don't need to use Html.Raw()