eRaisedToX
eRaisedToX

Reputation: 3361

MvcHtmlString.Create() method does not return Html encoded string

I must be missing something here, because this doc

says, MvcHtmlString.Create("someStringHere") returns html encoded string, but if i have something like MvcHtmlString.Create("<h1>myHeading</h1>") it still shows up as

myHeading

(as heading) and not as encoded text &lt;h1&gt;myHeading&lt;/h1&gt;

Then what is meant by the statement

MvcHtmlString.Create(String)
Creates an HTML-encoded string using the specified text value.

I am not able to understand, would be grateful if somebody could explain what does the doc mean and what's the difference between the encoding they are trying to refer to vs html encoding.

Thanks in advance!

Upvotes: 4

Views: 1005

Answers (1)

Luke
Luke

Reputation: 23680

I agree that the documentation seems misleading for MvcHtmlString.

However, MvcHtmlString is intended to be used when you don't want a string to be HTML encoded. The default behaviour of razor is to encode the output.

The Html string that you pass to it should already be encoded to ensure that it is outputted without additional encoding.

So assuming the following HTML helper:

public static class HtmlHelper
{     
    public static string GetHtmlString(this System.Web.Mvc.HtmlHelper htmlHelper)
    {
        return "<h1>myHeading</h1>";
    }

    public static MvcHtmlString GetMvcHtmlString(this System.Web.Mvc.HtmlHelper htmlHelper)
    {
        return MvcHtmlString.Create("<h1>myHeading</h1>");
    }
}

With the Razor view:

@Html.GetHtmlString()
@Html.GetMvcHtmlString()

The output would be:

&lt;h1&gt;myHeading&lt;/h1&gt

myHeading

Upvotes: 4

Related Questions