Search code examples
htmlasp.net-mvcrazorhtml-encode

Am I delusional about Html encoding?


I seem to be hitting a logical contradiction. I have a view with...

</br> in the markup and when I load the page it shows a new line. Inspecting the source I can see a </br>.

Then I put @Html.Raw("</br>") and in the source I get &lt;/br&gt;

However all the documentation says that by default razor will html encode all strings. So why does Html.Raw show an encoded string instead?

Shouldn't it be the other way around?


Solution

  • </br> is incorrect, you probably meant <br/>.

    This being said, here's how it works:

    <br/> generates <br/>
    @("<br/>") generates &lt;br/&gt;
    @Html.Raw("<br/>") generates <br/>
    

    The Html.Raw helper is used when you do not want to get HTML encoded output in the resulting HTML. By default the @ Razor function HTML encodes its argument.