Emitting Uncoded Razor Strings

As ScottGu reports on his post blog, “By default, the content emitted with the @ block is automatically HTML encoded to better protect against XSS attack scripts.” My question is: how can you output non-HTML string?

For 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... } 
+76
html-encode razor
Jul 28 '10 at 19:41
source share
5 answers

This is my favorite approach:

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

The source was a reference to Phil Haak Razor syntax: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

+108
Feb 07 2018-11-22T00:
source share

You can create a new instance of MvcHtmlString that does not receive HTML encoding.

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

Hopefully in the future Razor will become an easier way.

If you are not using MVC, you can try the following:

 @{ var html = new HtmlString("<a href='#'>Click me</a>") } 
+17
Jul 28 '10 at 20:46
source share

The new HtmlString is definitely the answer.

We looked at some other razor syntax changes, but in the end, none of them were actually shorter than the new HtmlString.

We can, however, wrap this in an assistant. Maybe...

 @Html.Literal("<p>something</p>") 

or

 @"<p>something</p>".AsHtml() 
+6
Jul 29 '10 at 1:15
source share

I also encountered this problem when switching our project to the new Razor viewing engine. The approach I took was a little different because we had to generate JSON data from C # and wanted to output it when the page loaded.

In the end, I implemented RawView, which was parallel to View inside cshtml files. Essentially, to get the raw string,

 @(new HtmlString(View.Foo)) // became @RawView.Foo 

This requires a few changes in the layout of the project, so I just wrote a blog post about it here . In short, this required a duplicate implementation of MVC DynamicViewDataDictionary and a new WebViewPage that contains RawView. I also went ahead and implemented an index statement in RawView to allow

 @RawView["Foo"] 

In a random case, someone needs to iterate over data with a list of keys.

Reading a nurse's comment would probably be better if I called it Literal instead of RawView.

0
Aug 18 '10 at 22:21
source share

I use ASP.NET MVC and Razor under Mono.

I could not get the HtmlHelper from System.Web.WebPages from System.Web.Mvc for some reason.

But I managed to output an uncoded string after declaring the model property as RazorEngine.Text.RawString . Now it displays as expected.

example

 @{ var txt = new RawString("some text with \"quotes\""); var txt2 = "some text with \"quotes\""; } <div>Here is unencoded text: @txt</div> <div>Here is encoded text: @txt2</div> 

Exit:

 <div>Here is unencoded text: some text with "quotes"</div> <div>Here is encoded text: some text with &quot;quotes&quot;</div> 
0
Feb 05 '19 at 13:11
source share



All Articles