Please navigate to the bottom of the page for Table of Contents

Friday, May 27, 2011

How to add HTML Server Controls to a Web Page Using ASP.NET

By default, HTML elements within an ASP.NET file are treated as literal text and you cannot reference them in server-side code. To make these elements programmatically accessible, you can indicate that an HTML element should be treated as a server control by adding the runat="server" attribute. You can also set the element's id attribute to give you way to programmatically reference the control. You then set attributes to declare property arguments and event bindings on server control instances.

To add an HTML server control

Type the HTML syntax of the element you want to use as a control. Include the normal HTML syntax for the element, and in addition, do the following:

  • Set the control's ID attribute (property) to a unique value for that page, unless the control is part of a complex control and will be repeated (as in Repeater, DataList, and GridView controls).
  • Set the runat="server" attribute to convert the element to a control.
<input id="Name" type="text" size="40" runat="server" />
<input type="submit" id="Enter" value="Enter" runat="server" />
Click <a id="Anchor1" runat="server" href="more.html">More </a> to see the next page



The code snippet above shows an HtmlInputText, an HtmlInputButton and HtmlAnchor server controls.


Note: All Html Server controls require that they be enclosed in a <form> server tag.

6 comments: