更新:2007 年 11 月
这些示例显示如何向页面中的元素添加 HTML 属性。第一个示例演示如何以声明方式向控件中添加属性。添加到控件中、但不与该控件的属性 (Property) 对应的任何属性 (Attribute) 都传递到浏览器。
第二个示例演示如何以编程方式向 Button 控件中添加属性和样式。第三个示例演示如何以编程方式向该页的 body 标记中添加属性,这需要您首先向该标记中添加 runat="server" 和 ID 属性。
示例
<body id="body" runat="server">
    <form id="form1" runat="server">
      <!-- Example1 --> 
      <input runat="server" id="Button1" type="button" onmouseover="rollover()" onmouseout="exitrollover()" />
    </form>
</body>
<script runat="server">
    Private Sub Page_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load
        ' Example 2
        Button1.Attributes.Add("onclick", "alert('hello, world')")
        Button1.Style.Add("background-color", "red")
        ' Example 3
        body.Attributes("bgcolor") = "lightblue"
    End Sub
</script>
<body id="body" runat="server">
    <form id="form1" runat="server">
      <!-- Example1 --> 
      <input runat="server" id="Button1" type="button" onmouseover="rollover()" onmouseout="exitrollover()" />
    </form>
</body>
<script runat="server">
    private void Page_Load()
    {
        //Example 2
        Button1.Attributes.Add("onclick", "alert('hello, world')");
        Button1.Style.Add("background-color", "red");
        //Example 3
        body.Attributes["bgcolor"] = "lightblue";
    }
</script>
编译代码
此示例需要:
- ASP.NET 网页。 
- 名为 Button1 的 ASP.NET Button 控件。 
- 位于该页的 body 标记中的属性 runat="server" 和 id="body"。 
可靠编程
没有验证您添加到控件上的属性;键/值对按原样呈现给浏览器。
在设置一个属性时,它重写同一名称的任何现有属性。(它不修改现有属性上的值)。因此,如果希望修改属性,必须先读取它,再修改它,然后将它重新添加到控件中。
如果某一特性在控件中是通过属性表示的,则该属性优先于您进行的特性设置。例如,如果您尝试使用 value 属性设置文本,则 TextBox 控件的 Text 属性优先。