48

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.

3
  • What does yourEncodedHtmlFromYouDatabase look like? I'm guessing that the HTML <h1>Test</h1> would actually be encoded something like this: &lt:h1&gt;Test&lt:/h1&gt;. Commented Jan 25, 2011 at 20:18
  • Actually, it would be more like using tags. I don't have the db ready yet, but that's what we're planning to do, so I'm looking for options. Commented Jan 25, 2011 at 20:27
  • This question for MVC2: stackoverflow.com/questions/2169805/… Commented Aug 1, 2011 at 19:46

3 Answers 3

98

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. As for security, I believe there's no such problem, since we'll be building this html ourselves.
12

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

Comments

0

You can display the HTML content or any MarkupString as in a very simple way follows:

@((MarkupString)YourModel.HTMLDetails)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.