How does Html.Raw MVC helper work?

那年仲夏 提交于 2019-11-29 13:31:55

Because encoded characters are HTML, and the Raw version of that string is the encoded one.


Html.Raw renders what it is given without doing any html encoding, so with ViewBag.div = "<div> Hello </div>";:

@Html.Raw(ViewBag.div);

Renders

<div> Hello </div>

However, when you have encoded characters in there, such as ViewBag.Something = "&gt;"; the raw version of that is &gt;. To get back to actual html you need to Html.Raw(HttpUtility.HtmlDecode(EncodedContent)); as you've said.

If Html.Raw did do the decoding then it would be confusing, and we would need something that didn't do it. ;-)

Html.Raw Method asks the Razor Engine to do not encode the special chars.

Razor Engine Encodes the special chars because it considers that you want to show them in the state you sent to it so it encodes the special chars and the browser decodes them again to show you them in the original state (the state that you sent to the razor engine), but if you use the Html.Raw that means that you ask the Razor engine to do not encode the special chars of your content and actually that does not mean that you ask it to decode your encoded content such the content you get from the database, it just ask the engine to do not encode the special chars so if you have an encoded content in the database you have to decode it using HttpUtility.HtmlDecode and then to ask the razor engine to do not encode the returned html tags by using Html.Raw.

For eaxmple if you have this content in your database

&lt;h1&gt;dklxf;&lt;span style="font-style: italic;"&gt;kldk;dlk&lt;span style="font-weight: bold;"&gt;dxl'f;dlxd'fdlf;ldk;dlkf&lt;/span&gt;&lt;/span&gt;&lt;/h1&gt;

now if you print it without using HTML.Raw the razor engine will encode the special chars in that content to be printed in the browser as it is but if you use HTML.Raw that means to do not do anything over the content so the browser will render them as a set of html tags which have a content inside it but not a formatted data, you will get some thing like:

<h1>dklxf;<span style="font-style: italic;">kldk;dlk<span style="font-weight: bold;">dxl'f;dlxd'fdlf;ldk;dlkf</span></span></h1></p>

but if you use Html.Raw(HttpUtility.HtmlDecode(EncodedContent)) then you will get a formatted data in your page like the following content because the content sent to the browser is html tags not entities

dklxf;kldk;dlkdxl'f;dlxd'fdlf;ldk;dlkf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!