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 runat="server"
and an ID attribute to the tag.
Example
Visual BasicВ | Copy Code |
---|---|
<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> |
C#В | Copy Code |
---|---|
<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"
andid="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