Tuesday, July 27, 2010

How to avoid attribute value encording in Asp.net 4.0

.Net 4.0 is encoding values when using Attributes.Add. In previous versions it didn't. With the new behaviour it is no longer possible to write attributes containing single quotes.
Here's an example.

<asp:TextBox ID="txtTest" runat="server" />

txtTest.Attributes.Add("onkeyup", "keyuphandler('hello')");
With the application pool framework version set to 2.0 it produces the desired result:
<input name="txtTest" type="text" id="txtTest" onkeyup="keyuphandler('hello')" />

With it set to 4.0 it produces an undesirable result:
<input name="txtTest" type="text" id="Text1" onkeyup="keyuphandler(&#39;hello&#39;)" />

.Net 4.0 needs to be fixed to allow the developer to write attribute values containing single quotes.
 Solution:
<system.web>
 <httpRuntime 
   encoderType="ActiveTest.HtmlAttributeEncoder" 

Than implement the class as below:
namespace ActiveTest
{
    public class HtmlAttributeEncoder : HttpEncoder
    {
        protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
        {
            value = value.Replace("\"""'");
            output.Write(value);
        }
    }
}
 

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...