Udostępnij za pośrednictwem


How to: Set HTML Attributes for Controls in ASP.NET Web Pages

These example show how to add HTML attributes to elements in the page. The first example shows how to add attributes to a control declaratively. Any attribute you add to a control that does not map to a property of that control is passed through to the browser.

The second example shows how to add an attribute and a style programmatically to a Button control. The third example shows how to add an attribute programmatically to the page's body tag, which requires that you first add runat="server" and an ID attribute to the tag.

Example

<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
        Button1.Attributes["bgcolor"] = "lightblue";
       
    }
</script>

Compiling the Code

This example requires:

  • An ASP.NET Web page.

  • An ASP.NET Button control named Button1.

  • The attributes runat="server" and id="body" in the page's body tag.

Robust Programming

No validation is done of the attributes you add to the control; the key/value pairs are rendered to the browser as-is.

When you set an attribute, it overrides any existing attribute of the same name. (It does not amend values onto an existing attribute.) Therefore, if you want to amend an attribute, you must first read it, amend it, and then add it back to the control.

If an attribute is represented in the control by a property, the property takes precedence over attribute settings that you make. For example, the Text property of a TextBox control takes precedence if you try to set the text using the value attribute.

See Also

Tasks

How to: Read HTML Attributes for Controls in Web Forms Pages