How does the Html.Raw MVC helper work?

I use Html.Raw to print the raw html content, for example, when I send some thing like ViewBag.div = "<div> Hello </div>";from the controller to the view side, it does not print the raw html content unless I use the method Html.Rawbut if I have encoded content like content encoded using jquery and inserted into the database, and I want to print it as a raw contents of the html, the method Html.Rawdoes not work, and I have to use HttpUtility.HtmlDecode(EncodedContent)before using Html.Rawso please, someone can explain why he is acting this way, and what is the correct The situation for the use of the method Html.Raw? or in another way, why Html.Rawdoesn't it work when it receives html objects as a parameter instead of html tags ?.

+4
source share
2 answers

Since the encoded characters are HTML, and the original version of this string is encoded.


Html.Raw displays what it sets without any html encoding, therefore with ViewBag.div = "<div> Hello </div>";:

@Html.Raw(ViewBag.div);

Visualizes

<div> Hello </div>

However, when you have encoded characters, for example ViewBag.Something = "&gt;";, the original version of this file &gt;. To return to the current html, you need Html.Raw(HttpUtility.HtmlDecode(EncodedContent));, as you said.

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

+12
source

Html.RawThe method asks the Razor Engine not to encode special characters .

Razor Engine , , , , , , (, ), Html.Raw , , Razor , , , , , , , , HttpUtility.HtmlDecode, html Html.Raw.

eaxmple,

&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;

, Html.Raw, , , , Html.Raw, , html, , , - :

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

Html.Raw(HttpUtility.HtmlDecode(EncodedContent)), , , , , , html-,

dklxf; < > kldk; DLK dxl'f; dlxd'fdlf; ; dlkf

+2

Source: https://habr.com/ru/post/1626680/


All Articles