10

I have a simple Model:

public class MyModel
{
     public string Text{get;set;}
}

I have a View, which renders Text property of MyModel:

<p>@Model.Text</p>

How can I render html tags from Text like tags? For example, I have Text "<b>Text</b>". I want to get bold text inside tag p as result:

Text

But Razor renders text as is:

<b>Text</b>
greatromul
  • 1,069
  • 2
  • 15
  • 42

1 Answers1

24

I think you need to use it like:

<p>@Html.Raw(Model.Text)</p>

You can find more info here on Phil Haack's blog.

anurse points out in the comments that you could, alternatively, set the type of the Text member of your View Model type as IHtmlString and just use @Model.Text to output it. ASP.NET MVC is clever enough to realize that the output should not be escaped.

Community
  • 1
  • 1
paracycle
  • 7,665
  • 1
  • 30
  • 34
  • 4
    This is a good solution when you want to render some content without HTML encoding occasionally. When you _know_ that a property of your model is always going to be HTML content that shouldn't be automatically encoded, you should make the type of that property IHtmlString. So if you change Text to be an IHtmlString instead of a string, you can type @Model.Text and Razor will output the tags properly. That way, it's clear that certain content is HTML and should be carefully sanitized to avoid HTML Injection Attacks. – Andrew Stanton-Nurse Apr 04 '11 at 17:37
  • @anurse: Wow, great comment. Didn't know that myself. I will update the answer to add this information as well. – paracycle Apr 05 '11 at 08:07