4

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!

2
  • you could use @Html.Encode(<MyHtmlStringHere>) instead. Commented May 10, 2019 at 10:28
  • @vikscool ,that's correct but my question was not to somehow solve my problem but to understand the use of MvcHtmlString and advantages this provides, and to point out that doc is mis-leading. Commented May 10, 2019 at 10:31

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, that's what.., it is totally mis-leading, I got so confused, got to understand this only after implementing myself. I don't know how can I get that doc updated to prevent others from getting this wrong information.
At the top of each of the documentation pages is an edit button. You could submit a pull request to the team at Microsoft with edits to the documentation :).
Oh..that's great!! didn't know of it.
Glad to have helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.