Display encoded html with razor

2019-01-08 09:47发布

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?

5条回答
祖国的老花朵
2楼-- · 2019-01-08 10:16

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);
}
查看更多
孤傲高冷的网名
3楼-- · 2019-01-08 10:18

You can also simply use the HtmlString class

    @(new HtmlString(Model.Content))
查看更多
We Are One
4楼-- · 2019-01-08 10:25

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>
查看更多
混吃等死
5楼-- · 2019-01-08 10:26

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>
查看更多
唯我独甜
6楼-- · 2019-01-08 10:28

Try this:

<div class='content'>    
   @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
</div>
查看更多
登录 后发表回答