More on Web Controls


Web controls spring from the same philosophy that led to the creation of Windows user interface controls 15 years ago. That architecture made Bill Gates the world’s richest man (even after the recent tech stock slide, according to Forbes.com). That’s my definition of a successful architecture; don’t know about yours. Microsoft stock must be holding more of its value.[2]

Input and output operations are highly repetitive. Prefabricating them— rolling them up in a capsule for any programmer to use—is a great idea. You kids today don’t know how lucky you are not to have to worry about writing your own button controls, for example, and painting the pixels differently to make the button look as if it’s been clicked. This not only saves an enormous amount of expensive programming time, but also makes every program’s user interface more consistent and thus easier for users to understand. Remember (I’m dating myself here) Windows 3.0, which didn’t contain a standard File Open dialog box? Every application programmer had to roll her own. It cost a lot, and every application’s implementation looked and worked a little (or a lot) differently. Windows 3.1 provided a File Open dialog box as part of the operating system, which made the lives of both programmers and users much easier. A Web control, in the ASP.NET sense of the word, is any type of user-interface-related programming logic that is capable of a) exposing a standard programming model to a development environment such as Visual Studio .NET, and b) rendering its appearance into HTML for display in a standard browser—more or less as a Windows control renders its appearance into Windows GDI function calls.

Controls exist to encapsulate reusable program logic dealing with user interfaces.

“But HTML already has controls,” you say. “Buttons and checkboxes and links. I use them all the time. Why do I have to learn a new set?” HTML does support a few controls as part of the language, but these have severe limitations. First, they’re not very numerous or very rich. A text box and a drop-down list box are about as far as they go. Compare their number to the controls advertised in Visual Studio magazine (formerly Visual Basic Programmers Journal) or their functionality to Visual Basic’s data-bound grid control. We’d like to be able to package a lot more functionality than the few and wimpy existing HTML elements provide. Second, they are hard to write code for. The communication channel between an HTML control and its run- time environment isn’t very rich. The Web Forms environment that Web controls inhabit contains an event-driven programming model similar to Visual Basic. It’s much easier to program, there’s much better support in development environments, and it abstracts away many of the differences from one browser to another. Web controls do more and are easier to program. Sounds decisive to me.

Web controls are richer, more numerous, and easier to program than standard HTML controls.

ASP.NET comes with the set of basic Web controls listed in Table 3-1. In addition, third-party vendors have written many controls for sale. Microsoft’s official ASP.NET Web site, http://www.asp.net, lists several hundred in its control gallery, and a Google search turns up dozens more. You can also write your own, which isn’t very hard. I discuss writing your own in a chapter you can download for free from http://www.introducingmicrosoft.net.

Web controls exist for many different functions.

Table 3-1: Web Forms Server Controls by Function

Function

Control

Description

Text display (read only)

Label

Displays text that users can’t directly edit.

Text edit

TextBox

Displays text entered at design time that can be edited by users at run time or changed programmatically.

Note: Although other controls allow users to edit text (for example, DropDownList), their primary purpose is not usually text editing.

Selection from a list

DropDownList

Allows users to either select from a list or enter text.

ListBox

Displays a list of choices. Optionally, the list can allow multiple selections.

Graphics display

Image

Displays an image.

AdRotator

Displays a sequence (predefined or random) of images.

Value setting

CheckBox

Displays a box that users can click to turn an option on or off.

RadioButton

Displays a single button that can be selected or not.

Date setting

Calendar

Displays a calendar to allow users to select a date.

Commands

Button

Used to perform a task.

LinkButton

Like a Button control but has the appearance of a hyperlink.

ImageButton

Like a Button control but incorporates an image instead of text.

Navigation controls

HyperLink

Creates Web navigation links.

Table controls

Table

Creates a table.

TableCell

Creates an individual cell within a table row.

TableRow

Creates an individual row within a table.

Grouping other controls

CheckBoxList

Creates a collection of check boxes.

Panel

Creates a borderless division on the form that serves as a container for other controls.

RadioButtonList

Creates a group of radio buttons. Inside the group, only one button can be selected.

List controls

Repeater

Displays information from a data set using a set of HTML elements and controls that you specify, repeating the elements once for each record in the data set.

DataList

Like the Repeater control but with more formatting and layout options, including the ability to display information in a table. The DataList control also allows you to specify editing behavior.

DataGrid

Displays information, usually data-bound, in tabular form with columns. Provides mechanisms to allow editing and sorting.

Place holding

PlaceHolder

Enables you to place an empty container control in the page and then dynamically add child elements to it at run time.

Literal

Renders static text into a Web page without adding any HTML elements.

XML

Reads XML and writes it into a Web Forms page at the location of the control.

When I placed controls on my form in the preceding example, Visual Studio .NET generated the statements in the .ASPX page, shown in Listing 3-3. Every statement that starts with <asp: > is a directive to the ASP.NET parser to create a control of the specified type when it generates the class file for the page. For example, in response to the statement <asp:label>, the parser creates a label control in the class. When the page is executed, the ASP.NET execution engine executes the event handler code on the page that interacts with the controls (fetching the time and setting the text and background color, as shown previously in Listing 3-2). Finally, the engine tells each control to render itself into HTML in accordance with its current properties, just as a Windows control renders itself into GDI calls in accordance with its current properties. The engine then writes the resulting HTML back to the client’s browser. Figure 3-7 shows this process schematically. Excerpts from the actual HTML sent to the client are shown in Listing 3-4.

The execution engine creates and uses the controls on the server side. The controls render their own HTML for the client.

Listing 3-3: Excerpts from .ASPX page created by Visual Studio .NET, showing control statements.

start example
<%@ Page Language="vb" AutoEventWireup="false"  Codebehind="WebForm1.aspx.vb" Inherits="SimplestASPVB.WebForm1"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" </HEAD> <body MS_POSITIONING="GridLayout"> <form  method="post" runat="server"> <asp:Label   style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 24px" runat="server">Time will be shown here</asp:Label> <asp:DropDownList   style="Z-INDEX: 102; LEFT: 136px; POSITION: absolute; TOP: 120px" runat="server" AutoPostBack="True"> <asp:ListItem Value="Black">Black</asp:ListItem> <asp:ListItem Value="Red">Red</asp:ListItem> <asp:ListItem Value="Green">Green</asp:ListItem> <asp:ListItem Value="Blue">Blue</asp:ListItem> </asp:DropDownList> <asp:Button   style="Z-INDEX: 103; LEFT: 184px; POSITION: absolute; TOP: 72px" runat="server" Text="Get Time"></asp:Button> <asp:CheckBox   style="Z-INDEX: 104; LEFT: 32px; POSITION: absolute; TOP: 72px" runat="server" Text="Show seconds?"></asp:CheckBox> <asp:Label   style="Z-INDEX: 105; LEFT: 32px; POSITION: absolute; TOP: 120px" runat="server">Text color:</asp:Label> </form> </body> </HTML>
end example

click to expand
Figure 3-7: .ASPX page execution engine sequence.

Listing 3-4: Excerpts from the HTML generated by the controls.

start example
 <span  style="color:Black;"> (time will be displayed here) </span> <span> <input type="checkbox"  name="CheckBox1" /> <label for="CheckBox1">Show Seconds ?</label> </span> <input type="submit" name="Button1" value="Get Time"  /> <p>Text Color: <select name="DropDownList1"   onchange="javascript:_ _doPostBack(‘DropDownList1’,’’)"> <option selected value="Black">Black</option> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select>
end example

Another great feature of the input controls in the Web controls package (list box, text box, check box, radio button, and so on) is that they can automatically remember the state in which the user left them when the page they are on makes a round-trip to the server. Microsoft calls this feature postback data. Observe the behavior of the check box control in the simplest example that I showed in the previous section. The check box correctly maintains its checked or unchecked state when the page is posted to the server for event handling and returned to the client browser afterward. I didn’t have to write any code to get this behavior, as I would have had to in classic HTML. Input Web controls automatically remember their state. During the postback operation, the data actually resides in a dedicated field in the HTTP header of the page. This is an automatic feature that you can’t turn off.

Input controls can maintain their contents and selection from one round- trip to another. Display controls can also maintain their state from one round-trip to another.

The display controls in the Web controls package, such as label, data list, data grid, and repeater, support their own version of property retention, called view state. Even though the user doesn’t set them to specific values, they still remember the state in which the program left them in the previous round trip. The .ASPX page environment automatically places a hidden input control called __VIEWSTATE on each of its pages. Web controls automatically serialize their state into this hidden control when the page is being destroyed and then retrieve their state when the page is next created, which is what you want most of the time. If you don’t want this, you easily can turn it off by setting the control’s MaintainState property to False.

Why does Microsoft use two separate mechanisms for maintaining control state, one for input controls and the other for display controls? Probably to make it easier for programmers to comply with the Principle of Least Astonishment, which states simply that astonishing a human user is not a good thing, therefore you should do it as seldom as possible. When a user types something into a field, she expects to see what she typed stay there until she does something that changes it. If an input control didn’t automatically maintain its state, a developer would have to write code to make it do so or astonish the heck out of his users. Since you have to do this all the time, Microsoft built it into the input control behavior and didn’t provide an off switch. On the other hand, a display control often doesn’t display what a user typed in. Instead, it usually shows the results of an internal computing operation. Sometimes you might want a display control to remember its state between operations, and sometimes you might not. Hence a different mechanism, this one with an off switch.

Web controls can also discover the specific browser on which the user will be viewing the page so that they can render their HTML to take advantage of different browser features if they want to. A good example of this is the range validator control, shown in Figure 3-8. Ensuring that a user-entered number falls between a certain maximum and minimum value is such a common task that Microsoft provides a Web control for it. You place the control on a form and set properties that tell it which text box to validate and what the maximum and minimum values are. When the control renders its HTML, it checks the version of the browser it’s running on. If it’s a newer browser that supports DHTML (specifically MSDOM 4.0 or later, and EcmaScript version 1.2 or later), the control renders HTML that includes a client-side script that will perform the numeric validation in the user’s browser before submitting the form to the server, thereby avoiding a network round-trip if a control contains invalid data. If all the data passes validation on the client, the form is submitted to the server. Somewhat counterintuitively, the validation operation is then repeated on the server, even though it passed on the client. This guarantees that the validation is performed before your server-side code runs, even if the control somehow messed up the client-side script on a flaky browser. If the control detects an older browser that doesn’t support DHTML, it automatically generates HTML code that performs a round-trip and validates on the server.

Web controls can detect the capabilities of the browser they are running on and render different code to take advantage of them.

click to expand
Figure 3-8: The range validator control.

Writing your own Web controls isn’t that hard because the .NET Framework contains prefabricated base classes from which you can inherit most of your control’s necessary infrastructure (sort of like MFC on steroids). I show several examples in a chapter about Web controls that’s available for free download at http://www.introducingmicrosoft.net.

You can write your own Web controls without too much trouble.

start sidebar
Tips from the Trenches

The process of creating controls, loading their state, running their code, and rendering their state obviously takes some amount of time. ASP.NET supports a number of different options for caching page output pages to reduce this time and improve throughput. You can cache an entire page if you want, but you can also cache the output of individual controls. You do this by adding the VaryByControl attribute to the <%@ OutputCache %> directive in the page’s .aspx file.

end sidebar

[2]As opposed to Sun, whose share price today will just barely buy you a good cup of coffee, as long as you don’t want too many extras in it.




Introducing Microsoft. NET
Introducing Microsoft .NET (Pro-Developer)
ISBN: 0735619182
EAN: 2147483647
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net