60

On my main page, I have the code @{Html.RenderPartial("_Partial1.cshtml");}, and on my Partial, I have an HTML string:

@{ 
    // The string is actually dynamic, not static. This is here for simplicity
    string abc="<div class=\"error\">abc</div>";
} 
@abc

I want to output abc with some CSS error styles, but I actually got <div class="error">abc</div> - of course, no styles there. How do I make it interpreted as HTML source code and not a string?

alex
  • 6,818
  • 9
  • 52
  • 103
cameron
  • 2,976
  • 3
  • 23
  • 35

2 Answers2

135

You can use the Html.Raw() method for that.

Nico Schertler
  • 32,049
  • 4
  • 39
  • 70
  • 8
    This was absolutely amazing. Tip if you have an .html file you want to render instead use: @Html.Raw(File.ReadAllText(Server.MapPath())) – cgatian Nov 19 '13 at 02:39
  • 2
    This is a dangerous answer. See https://en.wikipedia.org/wiki/Cross-site_scripting – Unw0und Jun 14 '15 at 03:25
  • 1
    Say I was to define a global variable in razor, and then use @html.Raw( on this variable because I want to define some markup in it and render on view. Is there a way someone can set a value to a Razor variable from the url? I just want to make sure this isn't vulnerable to XSS through URL injection.. Thanks! – eaglei22 Dec 14 '15 at 19:34
  • 2
    @user1794106 As long as you don't fill the variable from parts of the request, then no. Razor view variables are entirely evaluated on the server in a local scope. – Nico Schertler Dec 14 '15 at 20:38
  • this needs to be updated to warn the user of the potential security issues it can create! – czioutas Jul 21 '17 at 08:50
  • 1
    @Drakoumel And what potential security issues might that be? This method is not more dangerous than any other method that creates output. – Nico Schertler Jul 21 '17 at 08:54
  • Still relevant today – Piotr Kula Jun 02 '21 at 20:58
2

And if you are using model in your view than use:

@model YourApp.Models.YourModel
....

@Html.Raw(@Model.NameOfYourProperty)
Hrvoje
  • 13,566
  • 7
  • 90
  • 104