83

I store encoded HTML in the database.

The only way i could display it correctly is :

<div class='content'>    
   @MvcHtmlString.Create(HttpUtility.HtmlDecode(Model.Content));
</div>

It's ugly. Is there any better way to do this?

6 Answers 6

159

Try this:

<div class='content'>    
   @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
</div>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! This is better, but still not what I looking for.
I ended up making an extension method according this idea. @Html.RawDecode(Model.Content)
Just avoid ; in the end
This works but its so dirty... ended up making an Extention method with this wrapped, can someone explain why doesnt the .Raw just work?
Just be aware that this will introduce XSS vulnerabilities, so make sure you trust the input. If you need to store and render formatted text from users, use more suitable markup languages like markdown or some custom XML like editors.
50

Use Html.Raw(). Phil Haack posted a nice syntax guide at http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx.

<div class='content'>
    @Html.Raw( Model.Content )
</div>

1 Comment

Thank for the reply. But i think the Html.Raw() is 'display as it is, do not encode'. So if I use this, then I can't decode my html before I save it to the database. So it will display the user entered content without any 'security' check. So I think this is not the best solution.
9

this is pretty simple:

HttpUtility.HtmlDecode(Model.Content)

Another Solution, you could also return a HTMLString, Razor will output the correct formatting:

in the view itself:

@Html.GetSomeHtml()

in controller:

public static HtmlString GetSomeHtml()
{
    var Data = "abc<br/>123";
    return new HtmlString(Data);
}

Comments

8

You can also simply use the HtmlString class

    @(new HtmlString(Model.Content))

Comments

1

I store encoded HTML in the database.

Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:

<div class='content'>
    @Model.Content
</div>

Comments

0

I just got another case to display backslash \ with Razor and Java Script.

My @Model.AreaName looks like Name1\Name2\Name3 so when I display it all backslashes are gone and I see Name1Name2Name3

I found solution to fix it:

var areafullName =  JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.AreaName)))");

Don't forget to add @using Newtonsoft.Json on top of chtml page.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.