I am attempting to display literal HTML to the browser via my Razor View.
I have something like this in the code:
@Html.Encode("<!-- foo -->")
I was expecting the Html.Encode helper to return
<-- foo -->
but instead, it returns
&lt;!-- foo --&gt;
It appears as though the Encode helper encodes the string twice.
So, in order to get the output I want, I have to wrap the Encode helper with the Raw helper like this
@Html.Raw(Html.Encode("&开发者_运维百科lt;!-- foo -->"))
I'm new to MVC/Razor, so this behavior has me a bit confused as well as unsure as to whether or not my expectations of how Html.Encode should behave, is correct.
Moving forward w/ Razor, should I suck it up and get in the habit of wrapping Html.Encode with Html.Raw when I want to encode a string to HTML? Is there a "better" way to encode HTML string in Razor?
The @ syntax performs HTML encoding. By using @Html.Encode you're manually encoding, and then the @ encodes what you've already encoded.
So, to get what you want simply do
@("<!-- foo -->")
The @
operator already HTML encodes in Razor (unless the argument is an IHtmlString
instance). So you may try:
@("<!-- foo -->")
which renders:
<!-- foo -->
精彩评论