Coder Perfect

Razor render in ASP.NET MVC without encoding


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

Asked by SiberianGuy

Solution #1

Since the release of ASP.NET MVC 3, you can use:


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; }


<!-- this will be encoded -->
<!-- this will not be encoded -->
<!-- this will not be encoded either -->

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, HttpUtility is usually used. Encode the text of the link. You can use HttpUtility in that instance. When I used HtmlActionLink to decode the string that I intended to give, HtmlDecode(myString) worked for me. eg:


Answered by gutsy_guy

Post is based on