Sunday, January 4, 2009

Html Encode and Decode in .NET?


It is required some times to encode or decode the html contents.
Let us consider a label to which a java script code is assigned as text or content.

If we say
Aspx page:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HtmlEncode.aspx.cs" Inherits="HtmlEncode" ValidateRequest="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblText" runat="server" ></asp:Label>
</div>
</form>
</body>
</html>

Code behind page:-

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lblText.Text = "<script language='javascript'>alert('Hi friends an intresting post regarding html encode and decode');</script>";
}
}

Output:-






Actually expected result is that, the label should display the java script code as text, but the output is executed output of the java script function since label behaves as browser.
So to eradicate this we should encode the text before assigning to label.
Actual text =<script language='javascript'>alert('Hi friends an intresting post regarding html encode and decode');</script>

So when we encode the text content before rendering to label, the content could be again decoded to display the text as expected instead of exceting the script.
Output after html encoding
Code behind page :-
protected void Page_Load(object sender, EventArgs e)
{
lblData.Text = Server.HtmlEncode("<script language='javascript'>alert('Hi friends an intresting post regarding html encode and decode');</script>");
}
Output :-




1 comment:

Anonymous said...

IJDxYCHwIFA0dCUGQCBQ8WAh8CBQbCozkuNDhkAgQPDxYCHwIFB1Jlb3JkZXJkZAICD2QWAgICDxYCHwRoZAIDD2QWAmYPDxYCHwIFBDIwMTRkZAIEDw9kDxAWAWYWARYCHg5QYXJhbWV0ZXJWYWx1ZQUBMhYBZmRkAggPDxYCHwRoZGQYAgUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFYGN0bDAwJGN0bDAxJE1haW5Db250ZW50JENvbnRlbnRQbGFjZUhvbGRlcjEkb3JkZXJfaW5mbyRvcmRlcl9kZXRhaWwkT3JkZXJEZXRhaWxHcmlkJGN0bDAyJGRlbGV0ZQVTY3RsMDAkY3RsMDEkTWFpbkNvbnRlbnQkQ29udGVudFBsYWNlSG9sZGVyMSRvcmRlcl9pbmZvJG9yZGVyX2RldGFpbCRPcmRlckRldGFpbEdyaWQPPCsACgEIAgFkpVTLZVNAPwPsqncobpzJmgzTbO8=" name="__VIEWSTATE">