Thursday, August 12, 2010

How to change asp.net control attribute rendering and encording

Sometimes you may find when you add attributes to web controls like
this.txtName.Attributes.Add("onkeryup""javascript:CheckIt('email')");
.net renders the controls like
<input name="txtName" type="text" id="txtName" onkeryup="javascript:CheckIt(&#39;email&#39;)" />
As well sometimes you may get problems with do postback with options as asp.net renders
<input 
    type="submit" 
    name="btnSave" 
    value="Save" 
    onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(
        &quot;btnSave&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" 
    id="Submit1" />
In such cases, if this is not the case you are looking for, you may find it is useful to plug in custom attribute encorder and take control of how you want to render your attributes. This example below demonstrates how to plug in a custom url encorder and implment simple attribute encorder.
Web.config
<httpRuntime encoderType="ActiveTest.HtmlAttributeEncoder" ... />
Attribute encorder class
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...