user2250708
user2250708

Reputation: 173

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.

Upvotes: 1

Views: 201

Answers (2)

RickL
RickL

Reputation: 3393

Create a custom Helper (namespace referenced in Views):

    public static HtmlString TestHtmlString(this HtmlHelper html, string hText, string pText)
    {
        var h = new TagBuilder("h2");
        var p = new TagBuilder("p");
        h.InnerHtml = hText;
        p.InnerHtml = pText;
        return new HtmlString(h.ToString(TagRenderMode.Normal) + p.ToString(TagRenderMode.Normal));
    }

then you can use this in your Views:

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

Upvotes: 1

Evk
Evk

Reputation: 101483

You can use HtmlString like this:

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

Upvotes: 2

Related Questions