简体   繁体   中英

Asp.net MVC Razor not encoding html

My understanding is that the Razor markup will encode html strings, but I tried testing it out with following code in MVC view and it did not encode the html strings.

While the first encoded string is behaving correctly since its not handled by Razor engine, but the second string is not being encoded by Razor, and also the <> part at start in last string is not being encoded by Razor.

Question : Why are second and third strings not being encoded by Razor, or am I missing something about how Razor renders html strings?

Razor markup in a MVC View

&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
<br />
@("<script type='text/javascript'></script>")
<br />
@("<>&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;")

Rendering of above Razor markup

剃刀未编码html

UPDATE 1

I believe that the following is happening, but not sure (that is, Razor is encoding stuff but its not obvious to user who sees the browser rendered version)

I think the line just after first br that starts with @ is being encoded by Razor and then the browser is decoding it. Also, the third line just after the second br is being encoded by Razor with the already encoded part being doubly encoded, so when browser decodes it, it remains singly encoded but the <> was single encoded so it gets decoded by browser to <> . Does that sound right?

UPDATE 2

When I looked up in Chrome dev tool the response output, it indeed showed that Razor was encoding the strings in parenthesis. The output in Chrome dev tool for the request is as below. So, what I mentioned in UPDATE 1 is what is actually happening. The last string is doubly encoded as the the &gt; is appearing as &amp;gt; And the first string is singly encoded.

So, I was 100% correct in what I suspected was happening in UPDATE 1.

&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
<br />
&lt;script type=&#39;text/javascript&#39;&gt;&lt;/script&gt;
<br />
&lt;&gt;&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;

If you want to render string(which contains html) to your view as html not string than use @Html.Raw function

from MSDN @Html.Raw -- Returns markup that is not HTML encoded.

This will render html as text

&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

This will render as html and parse as html document

@Html.Raw("<script type='text/javascript'></script>")

This will render string as it is

@Html.Raw("<>&lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;")

Please let me know if your query fix,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM