Coder Perfect

Razor render in ASP.NET MVC without encoding

Problem

By default, Razor encodes strings. Is there a particular syntax for non-encoded rendering?

Asked by SiberianGuy

Solution #1

You can use: since ASP.NET MVC 3.

@Html.Raw(myString)

Answered by Lucas

Solution #2

@(new HtmlString(myString))

Answered by Matthew Vines

Solution #3

In addition to the @Html.Raw(string) technique already discussed, a MvcHtmlString will not be encoded. This is handy if you want to add your own extensions to the HtmlHelper or if you want to return a value from your view model that may contain html.

For instance, if your view model was:

public class SampleViewModel
{
  public string SampleString { get; set; }
  public MvcHtmlString SampleHtmlString { get; set; }
}

Use HtmlString for Core 1.0+ (and MVC 5+).

public class SampleViewModel
{
  public string SampleString { get; set; }
  public HtmlString SampleHtmlString { get; set; }
}

then

<!-- this will be encoded -->
<div>@Model.SampleString</div>
<!-- this will not be encoded -->
<div>@Html.Raw(Model.SampleString)</div>
<!-- this will not be encoded either -->
<div>@Model.SampleHtmlString</div>

Answered by Jonathan Moffatt

Solution #4

Use @Html.Raw() with caution, as it can lead to more encoding and security issues. I understand the use case because I had to do it myself, but proceed with caution… Allowing all text through isn’t a good idea. For example, only keep/convert specified character sequences while encoding everything else:

@Html.Raw(Html.Encode(myString).Replace("\n", "<br/>"))

Then you can rest assured that you haven’t introduced a security flaw, and that any special or foreign characters will be shown correctly in all browsers.

Answered by Tony Wall

Solution #5

In the case of ActionLink, the link text is usually encoded with HttpUtility.Encode. You can use HttpUtility.HtmlDecode(myString) in that situation; it worked for me when I used HtmlActionLink to decode the string I wanted to provide. eg:

  @Html.ActionLink(HttpUtility.HtmlDecode("myString","ActionName",..)

Answered by gutsy_guy

Post is based on https://stackoverflow.com/questions/4071602/asp-net-mvc-razor-render-without-encoding