asp.netasp.net-mvcrazorhtml-encode

How does Html.Raw MVC helper work?


I use the Html.Raw to print a 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 a raw html content unless I use the Html.Raw method but if I have an encoded content, like content encoded using jquery and inserted into the database and I want to print it as a raw html content the Html.Raw method does not work and I have to use HttpUtility.HtmlDecode(EncodedContent) before I use Html.Raw so please could anyone explain why it acts in this way and what is the proper situation to use Html.Raw method? or in another way, why Html.Raw does not work when it receives html entities as a parameter instead of html tags?.


Solution

  • 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. ;-)