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?

2
  • 1
    stackoverflow.com/questions/4281424/… Commented Mar 21, 2013 at 13:26
  • What's wrong with <div class="error">abc</div>? Commented Feb 11, 2016 at 20:00

2 Answers 2

136

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

Sign up to request clarification or add additional context in comments.

7 Comments

This was absolutely amazing. Tip if you have an .html file you want to render instead use: @Html.Raw(File.ReadAllText(Server.MapPath(<htmlpath>)))
This is a dangerous answer. See en.wikipedia.org/wiki/Cross-site_scripting
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!
@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.
@Drakoumel And what potential security issues might that be? This method is not more dangerous than any other method that creates output.
|
2

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

@model YourApp.Models.YourModel
....

@Html.Raw(@Model.NameOfYourProperty)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.