Html Encoding

Basic encoding

using OpenWaves;

...

var encoded = Html.Encode("This should be <em>html</em> encoded");  // Returns "This should be &lt;em&gt;html&lt;/em&gt; encoded"

Encoding options

Whenever you let your users enter text and want to provide a bit more then just plain text support, you need to think about how to encode what needs to be encoded and how to make sure that the rest works as expected. Html.Encode provides the following options you can pass in as a second argument. All HtmlEncodeOptions can be combined using binary or operator (|).

HtmlEncodeOptions.PreserveLineBreaks

Changes all occurences of '\n' character in the input text to </br> tag.

var encoded = Html.Encode("Line1\nLine2", HtmlEncodeOptions.PreserveLineBreaks); // Returns "Line1</br>Line2";

HtmlEncodeOptions.PreserveFormatting

Will not encode basic formatting tags (also makes sure they are all closed): <b>, <i>, <u>, <em>, <cite>, <ins>, <del>, <strong>

var encoded = Html.Encode("Big <strong>bang</strong>!", HtmlEncodeOptions.PreserveFormatting); // Returns "Big <strong>bang</string>!";

HtmlEncodeOptions.ActivateUrls,

Will look for text patterns that look like urls and "activate" them using <a> tag.
var encoded = Html.Encode("Visit www.makingwaves.com every day!", HtmlEncodeOptions.ActivateUrls); // Returns "Visit <a href=\"http://www.makingwaves.com\">www.makingwaves.com</a> every day!";

Last edited Aug 23, 2011 at 12:46 PM by mgrzyb, version 2

Comments

No comments yet.