Search code examples
c#asp.netasp.net-mvcrazorrazorengine

Getting unencoded html out of html helper


There have been many answer for this over the years and before anyone yells at me I've tried them all and just can't work. I'm using MVC 5, Razor 3, Visual Studio 2017. Here is a simplified test:

In my App_Code folder I have a SSLhelpers.cshtml file which contains:

@helper Macro(string Htext, string Ptext)
{
    <h2>@Htext</h2>
    <p>@Ptext</p>
}

In my view I have:

@SSLhelpers.Macro("This is my header", "This is my paragraph text. We should 
be <strong>bold</strong> here but we're not.")

The generated html is:

<h2>This is my header</h2>

<p>This is my paragraph text. We should be &lt;strong&gt;bold&lt;/strong&gt; 
here but we're not.</p>

How can I avoid the encoding?

Thank you.


Solution

  • You can use HtmlString like this:

    @helper Macro(string Htext, string Ptext)
    {
        <h2>@(new HtmlString(Htext))</h2>
        <p>@(new HtmlString(Ptext))</p>
    }