Convert IHtmlContent/TagBuilder to string in C#











up vote
16
down vote

favorite
2












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?










share|improve this question
























  • What about ToHtmlString? Also, where do you get IHtmlContent from?
    – shree.pat18
    Nov 12 '15 at 9:34








  • 1




    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
    – shree.pat18
    Nov 12 '15 at 10:00

















up vote
16
down vote

favorite
2












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?










share|improve this question
























  • What about ToHtmlString? Also, where do you get IHtmlContent from?
    – shree.pat18
    Nov 12 '15 at 9:34








  • 1




    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
    – shree.pat18
    Nov 12 '15 at 10:00















up vote
16
down vote

favorite
2









up vote
16
down vote

favorite
2






2





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?










share|improve this question















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?







c# asp.net asp.net-core asp.net-core-mvc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '15 at 12:10

























asked Nov 12 '15 at 8:41









zoaz

561726




561726












  • What about ToHtmlString? Also, where do you get IHtmlContent from?
    – shree.pat18
    Nov 12 '15 at 9:34








  • 1




    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
    – shree.pat18
    Nov 12 '15 at 10:00




















  • What about ToHtmlString? Also, where do you get IHtmlContent from?
    – shree.pat18
    Nov 12 '15 at 9:34








  • 1




    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
    – shree.pat18
    Nov 12 '15 at 10:00


















What about ToHtmlString? Also, where do you get IHtmlContent from?
– shree.pat18
Nov 12 '15 at 9:34






What about ToHtmlString? Also, where do you get IHtmlContent from?
– shree.pat18
Nov 12 '15 at 9:34






1




1




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
– shree.pat18
Nov 12 '15 at 10:00






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
– shree.pat18
Nov 12 '15 at 10:00














3 Answers
3






active

oldest

votes

















up vote
18
down vote



accepted










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, HtmlEncoder.Default);
return writer.ToString();
}


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.






share|improve this answer























  • Good answer.. This is what I was looking for.
    – zoaz
    Nov 13 '15 at 7:29






  • 11




    Does not work on asp.vnext core. use HtmlEncoder.Default instead
    – NucS
    Mar 30 '17 at 11:03










  • I updated the answer according to @NucS' comment
    – Kirill Rakhman
    7 hours ago


















up vote
22
down vote













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();
}





share|improve this answer




























    up vote
    9
    down vote













    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), just calling @Html.GetContent() is sufficient and Razor will take care of all the escaping business.






    share|improve this answer





















    • 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
      – Hunter Nelson
      Oct 3 at 3:54











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33667308%2fconvert-ihtmlcontent-tagbuilder-to-string-in-c-sharp%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    18
    down vote



    accepted










    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, HtmlEncoder.Default);
    return writer.ToString();
    }


    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.






    share|improve this answer























    • Good answer.. This is what I was looking for.
      – zoaz
      Nov 13 '15 at 7:29






    • 11




      Does not work on asp.vnext core. use HtmlEncoder.Default instead
      – NucS
      Mar 30 '17 at 11:03










    • I updated the answer according to @NucS' comment
      – Kirill Rakhman
      7 hours ago















    up vote
    18
    down vote



    accepted










    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, HtmlEncoder.Default);
    return writer.ToString();
    }


    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.






    share|improve this answer























    • Good answer.. This is what I was looking for.
      – zoaz
      Nov 13 '15 at 7:29






    • 11




      Does not work on asp.vnext core. use HtmlEncoder.Default instead
      – NucS
      Mar 30 '17 at 11:03










    • I updated the answer according to @NucS' comment
      – Kirill Rakhman
      7 hours ago













    up vote
    18
    down vote



    accepted







    up vote
    18
    down vote



    accepted






    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, HtmlEncoder.Default);
    return writer.ToString();
    }


    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.






    share|improve this answer














    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, HtmlEncoder.Default);
    return writer.ToString();
    }


    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 7 hours ago









    Kirill Rakhman

    18.9k875106




    18.9k875106










    answered Nov 12 '15 at 19:45









    Ketrex

    1,2381018




    1,2381018












    • Good answer.. This is what I was looking for.
      – zoaz
      Nov 13 '15 at 7:29






    • 11




      Does not work on asp.vnext core. use HtmlEncoder.Default instead
      – NucS
      Mar 30 '17 at 11:03










    • I updated the answer according to @NucS' comment
      – Kirill Rakhman
      7 hours ago


















    • Good answer.. This is what I was looking for.
      – zoaz
      Nov 13 '15 at 7:29






    • 11




      Does not work on asp.vnext core. use HtmlEncoder.Default instead
      – NucS
      Mar 30 '17 at 11:03










    • I updated the answer according to @NucS' comment
      – Kirill Rakhman
      7 hours ago
















    Good answer.. This is what I was looking for.
    – zoaz
    Nov 13 '15 at 7:29




    Good answer.. This is what I was looking for.
    – zoaz
    Nov 13 '15 at 7:29




    11




    11




    Does not work on asp.vnext core. use HtmlEncoder.Default instead
    – NucS
    Mar 30 '17 at 11:03




    Does not work on asp.vnext core. use HtmlEncoder.Default instead
    – NucS
    Mar 30 '17 at 11:03












    I updated the answer according to @NucS' comment
    – Kirill Rakhman
    7 hours ago




    I updated the answer according to @NucS' comment
    – Kirill Rakhman
    7 hours ago












    up vote
    22
    down vote













    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();
    }





    share|improve this answer

























      up vote
      22
      down vote













      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();
      }





      share|improve this answer























        up vote
        22
        down vote










        up vote
        22
        down vote









        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();
        }





        share|improve this answer












        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();
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jul 21 '16 at 14:48









        devfric

        4,05532548




        4,05532548






















            up vote
            9
            down vote













            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), just calling @Html.GetContent() is sufficient and Razor will take care of all the escaping business.






            share|improve this answer





















            • 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
              – Hunter Nelson
              Oct 3 at 3:54















            up vote
            9
            down vote













            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), just calling @Html.GetContent() is sufficient and Razor will take care of all the escaping business.






            share|improve this answer





















            • 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
              – Hunter Nelson
              Oct 3 at 3:54













            up vote
            9
            down vote










            up vote
            9
            down vote









            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), just calling @Html.GetContent() is sufficient and Razor will take care of all the escaping business.






            share|improve this answer












            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), just calling @Html.GetContent() is sufficient and Razor will take care of all the escaping business.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 1 '17 at 0:25









            vulcan raven

            24.2k54176




            24.2k54176












            • 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
              – Hunter Nelson
              Oct 3 at 3:54


















            • 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
              – Hunter Nelson
              Oct 3 at 3:54
















            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
            – Hunter Nelson
            Oct 3 at 3:54




            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
            – Hunter Nelson
            Oct 3 at 3:54


















             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33667308%2fconvert-ihtmlcontent-tagbuilder-to-string-in-c-sharp%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)