Display encoded html with razor

前端 未结 6 1684
心在旅途
心在旅途 2020-12-02 10:13

I store encoded HTML in the database.

The only way i could display it correctly is :

@MvcHtmlString.Create(HttpU
相关标签:
6条回答
  • 2020-12-02 10:48

    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>
    
    0 讨论(0)
  • 2020-12-02 10:51

    Try this:

    <div class='content'>    
       @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
    </div>
    
    0 讨论(0)
  • 2020-12-02 10:57

    You can also simply use the HtmlString class

        @(new HtmlString(Model.Content))
    
    0 讨论(0)
  • 2020-12-02 11:03

    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);
    }
    
    0 讨论(0)
  • 2020-12-02 11:06

    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>
    
    0 讨论(0)
  • 2020-12-02 11:07

    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.

    0 讨论(0)
提交回复
热议问题