Emitting unencoded strings in a Razor view

This is my favorite approach:

@Html.Raw("<p>my paragraph text</p>")

Source was Phil Haack's Razor syntax reference: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx


I'm using ASP.NET MVC and Razor under Mono.

I couldn't get HtmlHelper from System.Web.WebPages of System.Web.Mvc for some reasons.

But I managed to output unencoded string after declaring model's property as RazorEngine.Text.RawString. Now it outputs as expected.

Example

@{
    var txt = new RawString("some text with \"quotes\"");
    var txt2 = "some text with \"quotes\"";
}
<div>Here is unencoded text: @txt</div>
<div>Here is encoded text: @txt2</div>

Output:

<div>Here is unencoded text: some text with "quotes"</div>
<div>Here is encoded text: some text with &quot;quotes&quot;</div>

You can create a new instance of MvcHtmlString which won't get HTML encoded.

@{
  var html = MvcHtmlString.Create("<a href='#'>Click me</a>")
}

Hopefully there will be an easier way in the future of Razor.

If you're not using MVC, you can try this:

@{
  var html = new HtmlString("<a href='#'>Click me</a>")
}

new HtmlString is definitely the answer.

We looked into some other razor syntax changes, but ultimately none of them ended up really being any shorter than new HtmlString.

We may, however, wrap that up into a helper. Possibly...

@Html.Literal("<p>something</p>")

or

@"<p>something</p>".AsHtml()