CheckBox 控件新增加了两个属性:InputAttributes 和 LabelAttributes 。利用这两个属性,可以很方便地为label和input标签添加自定义属性,而使用 Attributes 则是不能完成这2个任务的。举一个例子,页面中定义一个asp:CheckBox:
<asp:CheckBox ID="cbTest" Text="CheckBox" runat="server" />
在后台代码中使用Attributes属性为其添加onclick事件:
cbTest.Attributes.Add("onclick", "checkBoxClick(this)");
然后浏览该页面,查看页面代码:
<input id="cbTest" type="checkbox" name="cbTest" onclick="checkBoxClick(this);" /><label for="cbTest">CheckBox</label>
后台程序为checkbox添加了onclick事件,但是label的事件无法添加,这是就可以使用LabelAttributes属性,为label添加事件。
cbTest.InputAttributes.Add("onclick", "checkBoxClick(this)");
cbTest.LabelAttributes.Add("onclick", "checkBoxClick(this)");
再次浏览该页面,查看页面代码:
<input id="cbTest" type="checkbox" name="cbTest" onclick="checkBoxClick(this)" /><label for="cbTest" onclick="checkBoxClick(this)">CheckBox</label>
发现label也有了onclick事件。在上面的代码中,我们已经使用了InputAttributes属性为checkbox添加事件,这个属性在此时的效果和使用Attributes属性添加事件得到的结果是一样的。但是他们还是会有些不同。在一些复杂的程序中,asp.net在解析aspx页面的时候,会为checkbox添加额外的<span>标签,此时Attributes属性添加的onclick事件就会被添加到span中,二并非input中,所以在此时,我们需用InputAttributes这个属性为input添加事件。