ASP.NET MVC Razor render without encoding ASP.NET MVC Razor render without encoding asp.net asp.net

ASP.NET MVC Razor render without encoding


Since ASP.NET MVC 3, you can use:

@Html.Raw(myString)


As well as the already mentioned @Html.Raw(string) approach, if you output an MvcHtmlString it will not be encoded. This can be useful when adding your own extensions to the HtmlHelper, or when returning a value from your view model that you know may contain html.

For example, if your view model was:

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

For Core 1.0+ (and MVC 5+) use HtmlString

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>