Is it possible to display raw Html from database in ASP.NET MVC 3?

前端 未结 2 1421
北荒
北荒 2020-11-29 06:05

I have a table in my db where one of the properties is an Html page (without the html, head and body tags), and I intend to put it in the middle of one of my views - say, I

相关标签:
2条回答
  • 2020-11-29 06:55

    You can also return a HTMLString and Razor will output the correct formatting, for example.

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

    This will allow you to display HTML

    0 讨论(0)
  • 2020-11-29 07:05

    All you need is: @Html.Raw(yourEncodedHtmlFromYouDatabase)

    I'm assuming that the html in the database has been properly sanitized (or at least from a reliable source), because if not, you could be opening yourself up to cross-site scripting attacks.

    The reason your approach didn't work is that Razor HTML-encodes output by default (every time you use @ to display something). Html.Raw tells Razor that you trust the HTML and you want to display it without encoding it (as it's already raw HTML).

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