Don’t call Html.Encode in Razor Pages

One of the unique features of ASP.Net WebPages (formerly Razor) is automatic HTML encoding.  All strings printed by embedded code nuggets (@ blocks) are automatically HTML-encoded.

In addition to this feature, Razor also includes the Html.Encode method, probably copied from ASP.Net MVC.  Calling this method naively leads to a nasty surprise – the string will be double-encoded!
To see why, look more closely at a typical call: @Html.Encode("<text>").  This Razor markup will call Html.Encode, which returns the string "&lt;text&gt;".   Since it returns a string and not an IHtmlString, the Razor engine will encode it again, and render &amp;lt;text&amp;gt;.

Careful thought indicates that this behavior is probably correct.  The programmer (hopefully) knows that Razor will escape its output, so the call to Html.Encode should be an attempt to display encoded text.  In fact, this is the simplest way to display HTML-encoded text in a Razor view. 

However, even if it is correct, the behavior is unexpected and should not be relied upon.  The unambiguous way to display encoded text is to call Html.Raw:

@Html.Raw(Html.Encode(Html.Encode("Double-encoded <html> text!")))

Although it is long and clunky, this clearly shows that the text will be double-encoded.

Exercise for the reader: Why is it also necessary to call Html.Raw?




In my opinion, on you will find useful information about writing graduation speech. It was useful to read for me and my college friends

I am a student of ASP.Net languages and found it really messy to learn. Due to my project, I have been looking to many magazines such as Coursework Writing Service to get some information and gather it to my notepad. After while, I got here and happy to learn some more facts.

We advise you to work the judgment in your economics assignment help online and support the Our online tutorial inspires an interactive whiteboard anywhere scholars and mentors. economics assignment help online

Hope you will keep on offering good content like this more often. I feel more and more people should know about this. Also, I agree on most of the points you have made.
Management Assignment Help

شركة مكافحة حشرات بالاحساء شركة مكافحة حشرات بالاحساء
شركة مكافحة النمل الابيض بالرياض شركة مكافحة النمل الابيض بالرياض

Post a Comment