ASP.NET Web Forms - Server Controls
Server controls are tags that can be understood by the server.
Limitations of Classic ASP
The code listed below is copied from the previous chapter:
Hello Runoob!
<%Response.Write(now())%>
The code above reflects the limitations of classic ASP: code blocks must be placed where you want the output to be displayed.
With classic ASP, it is impossible to separate executable code from the HTML page. This makes the page difficult to read and to maintain.
ASP.NET - Server Controls
ASP.NET has solved the above "spaghetti code" problem through server controls.
Server controls are tags that can be understood by the server.
There are three types of server controls:
- HTML Server Controls - HTML tags created
- Web Server Controls - new ASP.NET tags
- Validation Server Controls - used for input validation
ASP.NET - HTML Server Controls
HTML server controls are HTML tags that can be understood by the server.
HTML elements in an ASP.NET file are, by default, treated as text. To make these elements programmable, add the runat="server" attribute to the HTML element. This attribute indicates that the element will be treated as a server control. You also need to add an id attribute to identify the server control. The id reference can be used to manipulate the server control at runtime.
**Note:** All HTML server controls must be located within a
The executable code itself has been moved outside of the HTML.
ASP.NET - Web Server Controls
Web server controls are special ASP.NET tags that can be understood by the server.
Like HTML server controls, Web server controls are also created on the server, and they also require the runat="server" attribute to take effect. However, Web server controls do not need to map to any existing HTML element; they can represent more complex elements.
The syntax for creating a Web server control is:
In the example below, we declare a Button server control in the .aspx file. Then we create an event handler for the Click event to change the text on the button:
ASP.NET - Validation Server Controls
Validation server controls are used to validate user input. If the user input fails validation, an error message is displayed to the user.
Each validation control performs a specified type of validation (such as validating a specified value or a range of values).
By default, page validation is performed when the Button, ImageButton, or LinkButton control is clicked. You can set CausesValidation to false to prevent validation when the button control is clicked.
The syntax for creating a Validation server control is:
In the example below, we declare a TextBox control, a Button control, and a RangeValidator control in the .aspx file. If validation fails, the text "The value must be from 1 to 100!" will be displayed in the RangeValidator control: