How does Html.Raw MVC helper work?
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 = ">";
the raw version of that is >
. 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
<h1>dklxf;<span style="font-style: italic;">kldk;dlk<span style="font-weight: bold;">dxl'f;dlxd'fdlf;ldk;dlkf</span></span></h1>
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