Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 call a cotroller method that takes an argument, and return a view passing this html big string as the model. I searched for it (not much, I admit), and found the following method:

<%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>

That was found here in stackoverflow. When I tried a similar razor aproach, I ended up with this:

@System.Web.HttpUtility.HtmlDecode("<h1>Test</h1>")

That's the idea, but it didn't work quite as I planned.

like image 796
Bruno Machado - vargero Avatar asked Jan 25 '11 20:01

Bruno Machado - vargero


People also ask

What is HTML raw in ASP NET MVC?

The Html. Raw Helper Method is used to display HTML in Raw format i.e. without encoding in ASP.Net MVC Razor. Download Code Sample. Download Free Word/PDF/Excel API.

How do I display raw in HTML?

What is required to display Raw HTML code on a Webpage? In order to display HTML code on a webpage, you need to get rid of start tag < and end tag > symbol of every tag in your HTML code.

Why not use HTML Raw?

Raw can result in a XSS vulnerability being exploitable since an attacker can craft a special URL containing a malicious JavaScript payload that will be executed by the victim's browser if he or she sends an invalid 2FA confirmation code.


2 Answers

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

like image 191
Bennor McCarthy Avatar answered Sep 22 '22 23:09

Bennor McCarthy


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

like image 33
LiamB Avatar answered Sep 22 '22 23:09

LiamB