SiberianGuy
SiberianGuy

Reputation: 25282

ASP.NET MVC Razor render without encoding

Razor encodes string by default. Is there any special syntax for rendering without encoding?

Upvotes: 262

Views: 128434

Answers (6)

Jonathan Moffatt
Jonathan Moffatt

Reputation: 13457

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>

Upvotes: 36

gutsy_guy
gutsy_guy

Reputation: 327

In case of ActionLink, it generally uses HttpUtility.Encode on the link text. In that case you can use HttpUtility.HtmlDecode(myString) it worked for me when using HtmlActionLink to decode the string that I wanted to pass. eg:

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

Upvotes: 6

Hamid Shahid
Hamid Shahid

Reputation: 4616

You can also use the WriteLiteral method

Upvotes: 1

Tony Wall
Tony Wall

Reputation: 1412

Use @Html.Raw() with caution as you may cause more trouble with encoding and security. I understand the use case as I had to do this myself, but carefully... Just avoid allowing all text through. For example only preserve/convert specific character sequences and always encode the rest:

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

Then you have peace of mind that you haven't created a potential security hole and any special/foreign characters are displayed correctly in all browsers.

Upvotes: 11

Lucas
Lucas

Reputation: 17424

Since ASP.NET MVC 3, you can use:

@Html.Raw(myString)

Upvotes: 398

Matthew Vines
Matthew Vines

Reputation: 27561

@(new HtmlString(myString))

Upvotes: 63

Related Questions