Shahid Riaz Bhatti

if(my.work == “Interesting” || my.availableTime > my.workHours) { this.blog.Post();}

HTML Encoding

October 15
by Shahid Riaz Bhatti 15. October 2008 15:41
There are certain characters that have a special meaning in HTML. For example, the angle brackets (< >) are always used to create tags. This can cause problems if you actually want to use these characters as part of the content of your web page. For example, imagine you want to display this text on a web page:
Enter a word <here>
If you try to write this information to a page or place it inside a control, you end up with this instead:
Enter a word
The problem is that the browser has tried to interpret the <here> as an HTML tag. A similar problem occurs if you actually use valid HTML tags. For example, consider this text:
To bold text use the <b> tag.
Not only will the text <b> not appear, but the browser will interpret it as an instruction to make the text that follows bold. To overcome this automatic behavior, you need to convert potential problematic values to their HTML equivalents. For example, < becomes &lt; in your final HTML page, which the browser displays as the < character.
The following table lists some special characters that need to be encoded.
 
Result Description Encoding
  Non breaking space
&nbsp;
<
Less-than symbol
&lt
>
Greate-than symbol &gt
&
Ampersand

&amp

"
Quotation mark
&quote
 
Alternate solution:

  This problem can also be solved in another way i.e. by using the innerText property of the server control. InnerText property automatically converts any illegal characters into their HTML equivalent. However, this won’t help if you want to set a tag that contains a mix of embedded HTML tags and encoded characters. It also won’t be of any use for controls that don’t provide an InnerText property, such as the Label web control . In these cases, we can use the HttpServerUtility.HtmlEncode() method to replace the special characters. (Remember, an HttpServerUtility object is provided through the Page.Server property.)

 
 
Here’s an example:
// Will output as "Enter a word &lt;here&gt;" in the HTML file, but the
// browser will display it as "Enter a word <here>".

ctrl.InnerHtml = Server.HtmlEncode("Enter a word <here>");
// Or consider this example, which mingles real HTML tags with text that needs to be
// encoded:
ctrl.InnerHtml = "To <b>bold</b> text use the ";
ctrl.InnerHtml += Server.HtmlEncode("<b>") + " tag.";

 

RecentComments

Comment RSS

Most comments

supplynflshop supplynflshop
51 comments
tiffany-bracelets tiffany-bracelets
39 comments
AVI to iPad AVI to iPad
36 comments