ASP CheckBox asp:CheckBox Component Attributes

As I was few days ago, trying to add some Attributes to the ASP .NET Components (ListBox, CheckBox ...etc) from the Code Behind, I came to a very "funny" thing about how the ASP.NET is placing the Attributes to the Output HTML Code.

If you have sample Default.aspx Page, with following lines:

<form id="form1" runat="server">
      <asp:CheckBox ID="CheckBox1" runat="server"
      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox

... and the Code Behind looks like this:

protected void Page_Load(object sender, EventArgs e)
   this.CheckBox1.Attributes.Add("testAttribute", "123abc");
   this.CheckBox1.Attributes.Add("onClick", "DoSomething();");
   this.CheckBox1.Attributes.Add("onChange", "ChangeSomething();");

   this.TextBox1.Attributes.Add("testAttribute", "123abc");
   this.TextBox1.Attributes.Add("onClick", "DoSomething();");
   this.TextBox1.Attributes.Add("onChange", "ChangeSomething();");

The Code Behind lines above are setting one testAttribute which can be used as some identifier or can contain some value specific for the input field which can be very (only ?) usefull in Javascript for some Client-Side operations, and two more "events" used in Javascript.


After starting the page in Browser, the following Output HTML Code is generated by ASP.NET:

   <span testAttribute="123abc" onChange="ChangeSomething();">
input id="CheckBox1" type="checkbox" name="CheckBox1" onclick="DoSomething();" />
      <input name="TextBox1" type="text" id="TextBox1" testAttribute="123abc" onClick="DoSomething();" onChange="ChangeSomething();" />

As you can see, the Output HTML Code has transformed Checkbox Component into one <span /> element which contains testAttribute and onChange, and one <input type="checkbox" /> element containing only onClick Attribute.

ListBox Component looks much better, it contains all Attributes are in the same HTML Element.

I am not sure why could not all .NET Components be rendered in the same way, and I would like to know the answer becouse this approach of creating two HTML elements from one ASP Component which are containing only a part of Attributes, is very senseless and can cause much problems at the Client-Side Javascript operations.

Filed under: ,


# Damir Dobric Posts said:

Few days ago Armin has
posted the rendering problem of the ASP.NET 2.0 checkbox control. His problem...

Wednesday, May 31, 2006 10:37 AM

Leave a Comment