Display encoded html with razor

asp.net Mvc-3RazorHtml Encode

asp.net Mvc-3 Problem Overview


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?

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

Try this:

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

Solution 2 - asp.net Mvc-3

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>

Solution 3 - asp.net Mvc-3

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);
}

Solution 4 - asp.net Mvc-3

You can also simply use the HtmlString class

    @(new HtmlString(Model.Content))

Solution 5 - asp.net Mvc-3

> 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>

Solution 6 - asp.net Mvc-3

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjaniView Question on Stackoverflow
Solution 1 - asp.net Mvc-3AmitabhView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3tvanfossonView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3Muhammad SolimanView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3BellashView Answer on Stackoverflow
Solution 5 - asp.net Mvc-3McanicView Answer on Stackoverflow
Solution 6 - asp.net Mvc-3NoWarView Answer on Stackoverflow