开发者

Unexpected Behavior Using MVC Razor's Html.Encode HTML Helper

开发者 https://www.devze.com 2023-03-07 06:02 出处:网络
I am attempting to display literal HTML to the browser via my Razor View. I have something like this in the code:

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

&lt;-- foo --&gt;

but instead, it returns

&amp;lt;!-- foo --&amp;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:

&lt;!-- foo --&gt;
0

精彩评论

暂无评论...
验证码 换一张
取 消