Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emitting unencoded strings in a Razor view

As ScottGu says in his blog post «by default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios». My question is: how can you output a non-HTML-encoded string?

For the sake of simplicity, pls stick to this simple case:

@{
 var html = "<a href='#'>Click me</a>"
 // I want to emit the previous string as pure HTML code...
}
like image 967
hemme Avatar asked Jul 28 '10 19:07

hemme


People also ask

Is Cshtml a razor?

cshtml files are razorpages or MVC views, they does not contain any C#-written client-side code. If you wan to do so, you must use JavaScript. However, a . razor file, also know as a Razor component, can have C# written in it and run on client's browser.

What does @model represents in a razor view?

The @Model will contain all the data of the current page. So when you access a page on your site you can get data from that page with using the @Model. An example could be print the id of the page.

Which are the two basic types of transitions available in razor?

There are two basic types of transitions: code expressions and code blocks. Code expressions are evaluated and written to the response.

Which of these is the Razor view engine transition character?

There are only three transition characters with the Razor View Engine. The Razor View Engine is a bit slower than the ASPX View Engine. Razor provides a new view engine with streamlined code for focused templating. Razor's syntax is very compact and improves readability of the markup and code.


2 Answers

This is my favorite approach:

@Html.Raw("<p>my paragraph text</p>")

Source was Phil Haack's Razor syntax reference: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

like image 101
miguelv Avatar answered Oct 23 '22 18:10

miguelv


You can create a new instance of MvcHtmlString which won't get HTML encoded.

@{
  var html = MvcHtmlString.Create("<a href='#'>Click me</a>")
}

Hopefully there will be an easier way in the future of Razor.

If you're not using MVC, you can try this:

@{
  var html = new HtmlString("<a href='#'>Click me</a>")
}
like image 17
aolde Avatar answered Oct 23 '22 18:10

aolde