Section 21.5. Web Controls


21.5. Web Controls

This section introduces some of the Web controls located in the Standard section of the Toolbox (Fig. 21.9). Figure 21.15 summarizes some of the Web controls used in the chapter examples.

Figure 21.15. Commonly used Web controls.

Web Control

Description

Label

Displays text that the user cannot edit.

TextBox

Gathers user input and displays text.

Button

Triggers an event when clicked.

HyperLink

Displays a hyperlink.

DropDownList

Displays a drop-down list of choices from which a user can select an item.

RadioButtonList

Groups radio buttons.

Image

Displays images (e.g., GIF and JPG).


21.5.1. Text and Graphics Controls

Figure 21.16 depicts a simple form for gathering user input. This example uses all the controls listed in Fig. 21.15, except Label, which you used in Section 21.4. The code in Fig. 21.16 was generated by Visual Web Developer in response to dragging controls onto the page in Design mode. To begin, create an ASP.NET Web Site named WebControls. [Note: This example does not contain any functionalityi.e., no action occurs when the user clicks Register. In subsequent examples, we demonstrate how to add functionality to many of these Web controls.]

Figure 21.16. Web Form that demonstrates Web controls.

  1  <%-- Fig. 21.16: WebControls.aspx --%>  2  <%-- Registration form that demonstrates Web controls. --%>  3  <%@ Page Language="VB" AutoEventWireup="false"  4     CodeFile="WebControls.aspx.vb" Inherits="WebControls" %>  5  6  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  7     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  8  9  <html xmlns="http://www.w3.org/1999/xhtml"> 10  <head runat="server"> 11      <title>Web Controls Demonstration</title> 12  </head> 13  <body> 14     <form id="form1" runat="server"> 15     <div> 16        <h3>This is a sample registration form.</h3> 17        <p> 18           <em>Please fill in all fields and click Register. </em></p> 19        <p> 20           <asp:Image ID="userInformationImage" runat="server"               21              EnableViewState="False" ImageUrl="~/Images/user.png" /> &nbsp; 22           <span style="color: teal" >                                       23              Please fill out the fields below.</span>                       24        </p> 25        <table id="TABLE1"> 26           <tr> 27              <td style="width: 230px; height: 21px" valign="top"> 28                 <asp:Image ID="firstNameImage" runat= "server" 29                    EnableViewState="False" ImageUrl="~/Images/fname.png"/> 30                 <asp:TextBox ID="firstNameTextBox" runat="server" 31                    EnableViewState="False" ></asp:TextBox>        32              </td> 33              <td style="width: 231px; height: 21px" valign="top"> 34                 <asp:Image ID="lastNameImage" runat="server" 35                    EnableViewState="False" ImageUrl="~/Images/lname.png" /> 36                 <asp:TextBox ID="lastNameTextBox" runat="server" 37                    EnableViewState="False"></asp:TextBox> 38              </td> 39           </tr> 40           <tr> 41              <td style="width: 230px" valign="top"> 42                 <asp:Image ID="emailImage" runat="server" 43                    EnableViewState="False" ImageUrl="~/Images/email.png"/> 44                 <asp:TextBox ID="emailTextBox" runat="server" 45                    EnableViewState="False"></asp:TextBox> 46             </td> 47             <td style="width: 231px" valign="top"> 48                <asp:Image ID="phoneImage" runat="server" 49                   EnableViewState="False" ImageUrl="~/Images/phone.png"/> 50                <asp:TextBox ID="phoneTextBox" runat="server" 51                   EnableViewState="False"></asp:TextBox> 52                Must be in the form (555) 555-5555. 53             </td> 54          </tr> 55       </table> 56       <p> 57          <asp:Image ID="publicationsImage" runat="server" 58             EnableViewState="False" 59             ImageUrl="~/Images/publications.png"/>  60          <span style="color: teal"> 61             Which book would you like information about?</span> 62       </p> 63       <p> 64          <asp:DropDownList ID="booksDropDownList" runat="server" 65             EnableViewState="False" >                            66             <asp:ListItem>VisualBasic 2005 How to Program 3e     67                  </asp:ListItem>                                 68             <asp:ListItem>Visual C# 2005 How to Program 2e       69                  </asp:ListItem>                                 70             <asp:ListItem>Java How to Program 6e</asp:ListItem>  71             <asp:ListItem>C++How to Program 5e</asp:ListItem>     72             <asp:ListItem>XML How toProgram 1e</asp:ListItem>     73          </asp:DropDownList>                                     74       </p> 75       <p> 76          <asp:HyperLink ID="booksHyperLink" runat="server"              77             EnableViewState="False" NavigateUrl="http://www.deitel.com" 78             Target="_blank">                                            79             Click here to view more information about our books         80          </asp:HyperLink>                                               81       </p> 82       <p> 83          <asp:Image ID="osImage" runat="server" EnableViewState="False" 84             ImageUrl="~/Images/os.png" />   85          <span style="color: teal"> 86             Which operating system are you using?</span> 87        </p> 88        <p> 89             <asp:RadioButtonList ID="operatingSystemRadioButtonList" 90                runat="server" EnableViewState="False">                91                <asp:ListItem>Windows XP</asp:ListItem>               92                <asp:ListItem>Windows 2000</asp:ListItem>             93                <asp:ListItem>Windows NT</asp:ListItem>               94                <asp:ListItem>Linux</asp:ListItem>                    95                <asp:ListItem>Other</asp:ListItem>                    96             </asp:RadioButtonList>                                   97          </p> 98          <p> 99             <asp:Button ID="registerButton" runat="server" 100               EnableViewState="False" Text="Register"/>   101         </p> 102     </div> 103     </form> 104  </body> 105  </html> 

Before discussing the Web controls used in this ASPX file, we explain the XHTML that creates the layout seen in Fig. 21.16. The page contains an h3 heading element (line 16), followed by a series of additional XHTML blocks. We place most of the Web controls inside p elements (i.e., paragraphs), but we use an XHTML table element (lines 2555) to organize the Image and TextBox controls in the user information section of the page. In the preceding section, we described how to add heading elements and paragraphs visually without manipulating any XHTML in the ASPX file directly. Visual Web Developer allows you to add a table in a similar manner.

Adding an XHTML Table to a Web Form

To create a table with two rows and two columns in Design mode, select the Insert Table command from the Layout menu. In the Insert Table dialog that appears, select the Custom radio button. In the Layout group box, change the values of Rows and Columns to 2. By default, the contents of a table cell are aligned vertically in the middle of the cell. We changed the vertical alignment of all cells in the table by clicking the Cell Properties… button, then selecting top from the Vertical align combo box in the resulting dialog. This causes the content of each table cell to align with the top of the cell. Click OK to close the Cell Properties dialog, then click OK to close the Insert Table dialog and create the table. Once a table is created, controls and text can be added to particular cells to create a neatly organized layout.

Setting the Color of Text on a Web Form

Notice that some of the instructions to the user on the form appear in a teal color. To set the color of a specific piece of text, highlight the text and select Format > Foreground color…. In the Color Picker dialog, click the Named Colors tab and choose a color. Click OK to apply the color. Note that the IDE places the colored text in an XHTML span element (e.g., lines 2223) and applies the color using the span's style attribute.

Examining Web Controls on a Sample Registration Form

Lines 2021 of Fig. 21.16 define an Image control, which inserts an image into a Web page. The images used in this example are located in the chapter's examples directory. You can download the examples from www.deitel.com/books/vbforprogrammers2. Before an image can be displayed on a Web page using an Image Web control, the image must first be added to the project. We added an Images folder to this project (and to each example project in the chapter that uses images) by right clicking the location of the project in the Solution Explorer, selecting New Folder and entering the folder name Images. We then added each of the images used in the example to this folder by right clicking the folder, selecting Add Existing Item… and browsing for the files to add. You can also drag a folder full of images onto the project's location in the Solution Explorer to add the folder and all the images to the project.

The ImageUrl property (line 21) specifies the location of the image to display in the Image control. To select an image, click the ellipsis next to the ImageUrl property in the Properties window and use the Select Image dialog to browse for the desired image in the project's Images folder. When the IDE fills in the ImageUrl property based on your selection, it includes a tilde and forward slash (~/) at the beginning of the ImageUrlthis indicates that the Images folder is in the root directory of the project (i.e., http://localhost/WebControls, whose physical path is C:\Inetpub\wwwroot\WebControls).

Lines 2555 contain the table element created by the steps discussed previously. Each td element contains an Image control and a TextBox control, which allows you to obtain text from the user and display text to the user. For example, lines 3031 define a TextBox control used to collect the user's first name.

Lines 6473 define a DropDownList. This control is similar to the Windows ComboBox control. When a user clicks the drop-down list, it expands and displays a list from which the user can make a selection. Each item in the drop-down list is defined by a ListItem element (lines 6672). After dragging a DropDownList control onto a Web Form, you can add items to it using the ListItem Collection Editor. This process is similar to customizing a ListBox in a Windows application. In Visual Web Developer, you can access the ListItem Collection Editor by clicking the ellipsis next to the Items property of the DropDownList, or by using the DropDownList Tasks menu. You can open this menu by clicking the small arrowhead that appears in the upper-right corner of the control in Design mode (Fig. 21.17). This menu is called a smart tag menu. Visual Web Developer displays smart tag menus for many ASP.NET controls to facilitate common tasks. Clicking Edit Items... in the DropDownList Tasks menu opens the ListItem Collection Editor, which allows you to add ListItem elements to the DropDownList.

Figure 21.17. DropDownList Tasks smart tag menu.


The HyperLink control (lines 7680 of Fig. 21.16) adds a hyperlink to a Web page. The NavigateUrl property (line 77) of this control specifies the resource (i.e., http://www.deitel.com) that is requested when a user clicks the hyperlink. Setting the Target property to _blank specifies that the requested Web page should open in a new browser window. By default, HyperLink controls cause pages to open in the same browser window.

Lines 8996 define a RadioButtonList control, which provides a series of radio buttons from which the user can select only one. Like options in a DropDownList, individual radio buttons are defined by ListItem elements. Note that, like the DropDownList Tasks smart tag menu, the RadioButtonList Tasks smart tag menu also provides an Edit Items… link to open the ListItem Collection Editor.

The final Web control in Fig. 21.16 is a Button (lines 99100). A Button Web control represents a button that triggers an action when clicked. This control typically maps to an XHTML input element with attribute type set to "button". As stated earlier, clicking the Register button in this example does not do anything.

21.5.2. AdRotator Control

Web pages often contain product or service advertisements, which usually consist of images. Although Web site authors want to include as many sponsors as possible, Web pages can display only a limited number of advertisements. To address this problem, ASP.NET provides the AdRotator Web control for displaying advertisements. Using advertisement data located in an XML file, an AdRotator randomly selects an image to display and generates a hyperlink to the Web page associated with that image. Browsers that do not support images display alternate text that is specified in the XML document. If a user clicks the image or substituted text, the browser loads the Web page associated with that image.

Demonstrating the AdRotator Web Control

Figure 21.18 demonstrates the AdRotator Web control. In this example, the "advertisements" that we rotate are the flags of 10 countries. When a user clicks the displayed flag image, the browser is redirected to a Web page containing information about the country that the flag represents. If a user refreshes the browser or requests the page again, one of the eleven flags is again chosen at random and displayed.

Figure 21.18. Web Form that demonstrates the AdRotator Web control.

  1  <%-- Fig. 21.18: FlagRotator.aspx --%>  2  <%-- A Web Form that displays flags using an AdRotator control. --%>  3  <%@ Page Language="VB" AutoEventWireup="false"  4      CodeFile="FlagRotator.aspx.vb" Inherits="FlagRotator" %>  5  6  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  7     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  8  9  <html xmlns="http://www.w3.org/1999/xhtml" > 10  <head runat="server"> 11      <title>Flag Rotator</title> 12  </head> 13  <body background="Images/background.png"> 14      <form id="form1" runat="server"> 15      <div> 16         <h3>AdRotator Example </h3> 17         <p> 18            <asp:AdRotator ID="countryRotator" runat="server"      19               DataSourceID="adXmlDataSource" />                   20            <asp:XmlDataSource ID="adXmlDataSource" runat="server" 21               DataFile="~/App_Data/AdRotatorInformation.xml">     22            </asp:XmlDataSource>                                   23         </p> 24      </div> 25      </form> 26  </body> 27  </html> 

The ASPX file in Fig. 21.18 is similar to that in Fig. 21.4. However, instead of XHTML text and a Label, this page contains XHTML text (the H3 element in line 17) and an AdRotator control named countryRotator (lines 1819). This page also contains an XmlDataSource control (lines 2022), which supplies the data to the AdRotator control. The background attribute of the page's body element (line 13) is set to the image background.png, located in the project's Images folder. To specify this file, click the ellipsis provided next to the Background property of DOCUMENT in the Properties window and use the resulting dialog to select background.png from the Images folder. The images and XML file used in this example are both located in the chapter's examples directory.

You do not need to add any code to the code-behind file, because the AdRotator control "does all the work." The output depicts two different requests. Figure 21.18(a) shows the first time the page is requested, when the American flag is shown. In the second request, as shown in Figure 21.18(b), the French flag is displayed. Figure 21.18(c) depicts the Web page that loads when the French flag is clicked.

Connecting Data to an AdRotator Control

An AdRotator control accesses an XML file (presented shortly) to determine what advertisement (i.e., flag) image, hyperlink URL and alternate text to display and include in the page. To connect the AdRotator control to the XML file, we create an XmlDataSource controlone of several ASP.NET data controls (found in the Data section of the Toolbox) that encapsulate data sources and make such data available for Web controls. An XmlDataSource references an XML file containing data that will be used in an ASP.NET application. Later in the chapter, you will learn more about data-bound Web controls, as well as the SqlDataSource control, which retrieves data from a SQL Server database, and the ObjectDataSource control, which encapsulates an object that makes data available.

To build this example, we first add the XML file AdRotatorInformation.xml to the project. Each project created in Visual Web Developer contains an App_Data folder, which is intended to store all the data used by the project. Right click this folder in the Solution Explorer and select Add Existing Item…, then browse for AdRotatorInformation.xml on your computer. We provide this file in the chapter's examples directory in the subdirectory named exampleXMLFiles.

After adding the XML file to the project, drag an AdRotator control from the Toolbox to the Web Form. The AdRotator Tasks smart tag menu will open automatically. From this menu, select <New Data Source…> from the Choose Data Source drop-down list to start the Data Source Configuration Wizard. Select XML File as the data-source type. This causes the wizard to create an XmlDataSource with the ID specified in the bottom half of the wizard dialog. We set the ID of the control to adXmlDataSource. Click OK in the Data Source Configuration Wizard dialog. The Configure Data Source - adXmlDataSource dialog appears next. In this dialog's Data File section, click Browse… and, in the Select XML File dialog, locate and select the XML file you added to the App_Data folder. Click OK to exit this dialog, then click OK to exit the Configure Data Source - adXmlDataSource dialog. After completing these steps, the AdRotator is configured to use the XML file to determine which advertisements to display.

Examining an XML File Containing Advertisement Information

XML document AdRotatorInformation.xml (Fig. 21.19)or any XML document used with an AdRotator controlmust contain one Advertisements root element (lines 494). Within that element can be several Ad elements (e.g., lines 512), each of which provides information about a different advertisement. Element ImageUrl (line 6) specifies the path (location) of the advertisement's image, and element NavigateUrl (lines 79) specifies the URL for the Web page that loads when a user clicks the advertisement. Note that we reformatted this file for presentation purposes. The actual XML file cannot contain any whitespace before or after the URL in the NavigateUrl element, or the whitespace will be considered part of the URL, and the page will not load properly.

Figure 21.19. XML file containing advertisement information used in AdRotator example.

  1  <?xml version="1.0" encoding="utf-8"?>  2  <!-- Fig. 21.19: AdRotatorInformation.xml -->  3  <!-- XML file containing advertisement information. -->  4  <Advertisements>  5     <Ad>  6        <ImageUrl>Images/france.png</ImageUrl>  7        <NavigateUrl>  8           http://www.odci.gov/cia/publications/factbook/geos/fr.html  9        </NavigateUrl> 10        <AlternateText>France Information</AlternateText> 11        <Impressions>1</Impressions> 12     </Ad> 13 14     <Ad> 15        <ImageUrl>Images/germany.png</ImageUrl> 16        <NavigateUrl> 17           http://www.odci.gov/cia/publications/factbook/geos/gm.html 18        </NavigateUrl> 19        <AlternateText>Germany Information</AlternateText> 20        <Impressions>1</Impressions> 21     </Ad> 22 23     <Ad> 24        <ImageUrl>Images/italy.png</ImageUrl> 25        <NavigateUrl> 26           http://www.odci.gov/cia/publications/factbook/geos/it.html 27        </NavigateUrl> 28        <AlternateText>Italy Information</AlternateText> 29        <Impressions>1</Impressions> 30     </Ad> 31 32     <Ad> 33        <ImageUrl>Images/spain.png</ImageUrl> 34        <NavigateUrl> 35           http://www.odci.gov/cia/publications/factbook/geos/sp.html 36        </NavigateUrl> 37        <AlternateText>Spain Information</AlternateText> 38        <Impressions>1</Impressions> 39     </Ad> 40 41     <Ad> 42        <ImageUrl>Images/latvia.png</ImageUrl> 43        <NavigateUrl> 44           http://www.odci.gov/cia/publications/factbook/geos/lg.html 45        </NavigateUrl> 46        <AlternateText>Latvia Information</AlternateText> 47        <Impressions>1</Impressions> 48     </Ad> 49 50     <Ad> 51        <ImageUrl>Images/peru.png</ImageUrl> 52        <NavigateUrl> 53           http://www.odci.gov/cia/publications/factbook/geos/pe.html 54        </NavigateUrl> 55        <AlternateText>Peru Information</AlternateText> 56        <Impressions>1</Impressions> 57     </Ad> 58 59     <Ad> 60        <ImageUrl>Images/senegal.png</ImageUrl> 61        <NavigateUrl> 62           http://www.odci.gov/cia/publications/factbook/geos/sg.html 63        </NavigateUrl> 64        <AlternateText>Senegal Information</AlternateText> 65        <Impressions>1</Impressions> 66     </Ad> 67 68     <Ad> 69        <ImageUrl>Images/sweden.png</ImageUrl> 70        <NavigateUrl> 71           http://www.odci.gov/cia/publications/factbook/geos/sw.html 72        </NavigateUrl> 73        <AlternateText>Sweden Information</AlternateText> 74        <Impressions>1</Impressions> 75     </Ad> 76 77     <Ad> 78        <ImageUrl>Images/thailand.png</ImageUrl> 79        <NavigateUrl> 80           http://www.odci.gov/cia/publications/factbook/geos/th.html 81        </NavigateUrl> 82        <AlternateText>Thailand Information</AlternateText> 83        <Impressions>1</Impressions> 84     </Ad> 85 86     <Ad> 87        <ImageUrl>Images/unitedstates.png</ImageUrl> 88        <NavigateUrl> 89           http://www.odci.gov/cia/publications/factbook/geos/us.html 90        </NavigateUrl> 91        <AlternateText>United States Information</AlternateText> 92        <Impressions>1</Impressions> 93     </Ad> 94  </Advertisements> 

The AlternateText element (line 10) nested in each Ad element contains text that displays in place of the image when the browser cannot locate or render the image for some reason (i.e., the file is missing, or the browser is not capable of displaying it), or to assist the visually impaired. The AlternateText element's text is also a tooltip that Internet Explorer displays when a user places the mouse pointer over the image (Fig. 21.18). The Impressions element (line 56) specifies how often a particular image appears, relative to the other images. An advertisement that has a higher Impressions value displays more frequently than an advertisement with a lower value. In our example, the advertisements display with equal probability, because the value of each Impressions element is set to 1.

21.5.3. Validation Controls

This section introduces a different type of Web control, called a validation control (or validator), which determines whether the data in another Web control is in the proper format. For example, validators could determine whether a user has provided information in a required field or whether a ZIP-code field contains exactly five digits. Validators provide a mechanism for validating user input on the client. When the XHTML for our page is created, the validator is converted into ECMAScript[1] that performs the validation. ECMAScript is a scripting language that enhances the functionality and appearance of Web pages and is typically executed on the client. However, some clients do not support scripting or disable scripting. So, for security reasons, validation is always performed on the serverwhether or not scripting is enabled on the client.

[1] ECMAScript (commonly known as JavaScript) is a scripting standard developed by ECMA International. Both Netscape's JavaScript and Microsoft's JScript implement the ECMAScript standard, but each provides additional features beyond the specification. For information on the current ECMAScript standard, visit www.ecma-international.org/publications/standards/Ecma-262.htm. See www.mozilla.org/js for information on JavaScript and msdn.microsoft.com/library/en-us/script56/html/js56jsoriJScript.asp for information on JScript.

Validating Input in a Web Form

The example in this section prompts the user to enter a name, e-mail address and phone number. A Web site could use a form like this to collect contact information from site visitors. After the user enters any data, but before the data is sent to the Web server, validators ensure that the user entered a value in each field and that the e-mail address and phone number values are in an acceptable format. In this example, (555) 123-4567, 555-123-4567 and 123-4567 are all considered valid phone numbers. Once the data is submitted, the Web server responds by displaying an appropriate message and an XHTML table repeating the submitted information. Note that a real business application would typically store the submitted data in a database or in a file on the server. We simply send the data back to the form to demonstrate that the server received the data.

Figure 21.20 presents the ASPX file. Like the Web Form in Fig. 21.16, this Web Form uses a table to organize the page's contents. Lines 2425, 3637 and 5859 define TextBoxes for retrieving the user's name, e-mail address and phone number, respectively, and line 78 defines a Submit button. Lines 8082 create a Label named outputLabel that displays the response from the server when the user successfully submits the form. Notice that outputLabel's Visible property is initially set to False (line 81), so the Label does not appear in the client's browser when the page loads for the first time.

Figure 21.20. Validators used in a Web Form that retrieves user's contact information.

  1  <%-- Fig. 21.20: Validation.aspx --%>  2  <%-- Form that demonstrates using validators to validate user input. --%>  3  <%@ Page Language="VB" AutoEventWireup="false"  4     CodeFile="Validation.aspx.vb" Inherits="Validation" %>  5  6  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  7     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  8  9  <html xmlns="http://www.w3.org/1999/xhtml" > 10  <head runat="server"> 11      <title>Demonstrating Validation Controls</title> 12  </head> 13  <body> 14     <form id="form1" runat="server"> 15     <div> 16        Please fill out the following form.<br /><em>All fields are 17        required and must contain valid information.</em><br /> 18        <br /> 19        <table> 20           <tr> 21               <td style="width: 100px" valign="top"> 22                  Name:</td> 23               <td style="width: 450px" valign="top"> 24                 <asp:TextBox ID="nameTextBox" runat="server"> 25                 </asp:TextBox><br /> 26                <asp:RequiredFieldValidator                          27                   ID="nameInputValidator" runat="server"            28                   ControlToValidate="nameTextBox" Display="Dynamic" 29                   ErrorMessage="Please enter your name.">           30                </asp:RequiredFieldValidator>                        31             </td> 32          </tr> 33          <tr> 34             <td style="width: 100px" valign="top">E-mail address:</td> 35             <td style="width: 450px" valign="top"> 36                <asp:TextBox ID="emailTextBox" runat="server" > 37                </asp:TextBox> 38                &nbsp; e.g., user@domain.com<br /> 39                <asp:RequiredFieldValidator                               40                   ID="emailInputValidator" runat="server"                41                   ControlToValidate="emailTextBox" Display="Dynamic"     42                   ErrorMessage="Please enter your e-mail address.">      43                </asp:RequiredFieldValidator>                             44                <asp:RegularExpressionValidator                           45                   ID="emailFormatValidator" runat="server"               46                   ControlToValidate="emailTextBox" Display="Dynamic"     47                   ErrorMessage=                                          48                      "Please enter an e-mail address in a valid format." 49                   ValidationExpression=                                  50                      "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" >    51                </asp:RegularExpressionValidator>                         52             </td> 53          </tr> 54          <tr> 55             <td style="width: 100px; height: 21px" valign="top"> 56                Phone number: </td> 57             <td style="width: 450px; height: 21px" valign="top"> 58                <asp:TextBox ID="phoneTextBox" runat="server"> 59                </asp:TextBox> 60                &nbsp; e.g., (555) 555-1234 <br /> 61                <asp:RequiredFieldValidator                            62                   ID="phoneInputValidator" runat="server"             63                   ControlToValidate="phoneTextBox" Display="Dynamic"  64                   ErrorMessage="Please enter your phone number.">     65                </asp:RequiredFieldValidator>                          66                <asp:RegularExpressionValidator                        67                   ID="phoneFormatValidator" runat="server"            68                   ControlToValidate="phoneTextBox" Display="Dynamic"  69                   ErrorMessage=                                       70                      "Please enter a phone number in a valid format." 71                   ValidationExpression=                               72                        "((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" >       73                </asp:RegularExpressionValidator>                      74             </td> 75          </tr> 76       </table> 77       <br /> 78       <asp:Button ID="submitButton" runat="server" Text="Submit" /><br /> 79       <br /> 80       <asp:Label ID="outputLabel" runat="server" 81          Text="Thank you for your submission." Visible="False"> 82        </asp:Label> 83     </div> 84     </form> 85  </body> 86  </html> 

(a)

(b)

(c)

(d)

Using RequiredFieldValidator Controls

In this example, we use three RequiredFieldValidator controls (found in the Validation section of the Toolbox) to ensure that the name, e-mail address and phone number TextBoxes are not empty when the form is submitted. A RequiredFieldValidator makes an input control a required field. If such a field is empty, validation fails. For example, lines 2630 define RequiredFieldValidator nameInputValidator, which confirms that nameTextBox is not empty. Line 28 associates nameTextBox with nameInputValidator by setting the validator's ControlToValidate property to nameTextBox. This indicates that nameInputValidator verifies the nameTextBox's contents. We set the value of this property (and the validator's other properties) by selecting the validator in Design mode and using the Properties window to specify property values. Property ErrorMessage's text (line 29) is displayed on the Web Form if the validation fails. If the user does not input any data in nameTextBox and attempts to submit the form, the ErrorMessage text is displayed in red. Because we set the validator's Display property to Dynamic (line 28), the validator is displayed on the Web Form only when validation fails. Space is allocated dynamically when validation fails, causing the controls below the validator to shift downward to accommodate the ErrorMessage, as seen in Fig. 21.20(a)(c).

Using RegularExpressionValidator Controls

This example also uses RegularExpressionValidator controls to match the e-mail address and phone number entered by the user against regular expressions. (Regular expressions are introduced in Chapter 16.) These controls determine whether the e-mail address and phone number were each entered in a valid format. For example, lines 4451 create a RegularExpressionValidator named emailFormatValidator. Line 46 sets property ControlToValidate to emailTextBox to indicate that emailFormatValidator verifies the emailTextBox's contents.

A RegularExpressionValidator's ValidationExpression property specifies the regular expression that validates the ControlToValidate's contents. Clicking the ellipsis next to property ValidationExpression in the Properties window displays the Regular Expression Editor dialog, which contains a list of Standard expressions for phone numbers, ZIP codes and other formatted information. You can also write your own custom expression. For the emailFormatValidator, we selected the standard expression Internet e-mail address, which uses the validation expression

 \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 


This regular expression indicates that an e-mail address is valid if the part of the address before the @ symbol contains one or more word characters (i.e., alphanumeric characters or underscores), followed by zero or more strings comprised of a hyphen, plus sign, period or apostrophe and additional word characters. After the @ symbol, a valid e-mail address must contain one or more groups of word characters potentially separated by hyphens or periods, followed by a required period and another group of one or more word characters potentially separated by hyphens or periods. For example, bob.white@email.com, bob-white@my-email.com and bob's-personal.email@white.email.com are all valid e-mail addresses. If the user enters text in the emailTextBox that does not have the correct format and either clicks in a different text box or attempts to submit the form, the ErrorMessage text is displayed in red.

We also use RegularExpressionValidator phoneFormatValidator (lines 6673) to ensure that the phoneTextBox contains a valid phone number before the form is submitted. In the Regular Expression Editor dialog, we select U.S. phone number, which assigns

 ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4} 


to the ValidationExpression property. This expression indicates that a phone number can contain a three-digit area code either in parentheses and followed by an optional space or without parentheses and followed by required hyphen. After an optional area code, a phone number must contain three digits, a hyphen and another four digits. For example, (555) 123-4567, 555-123-4567 and 123-4567 are all valid phone numbers.

If all five validators are successful (i.e., each TextBox is filled in, and the e-mail address and phone number provided are valid), clicking the Submit button sends the form's data to the server. As shown in Fig. 21.20(d), the server then responds by displaying the submitted data in the outputLabel (lines 8082).

Examining the Code-Behind File for a Web Form That Receives User Input

Figure 21.21 depicts the code-behind file for the ASPX file in Fig. 21.20. Notice that this code-behind file does not contain any implementation related to the validators. We say more about this soon.

Figure 21.21. Code-behind file for a Web Form that obtains a user's contact information.

  1  ' Fig. 21.21: Validation.aspx.vb  2  ' Code-behind file for the form demonstrating validation controls.  3  Partial Class Validation  4     Inherits System.Web.UI.Page  5  6     ' Page_Load event handler executes when the page is loaded  7     Protected Sub Page_Load(ByVal sender As Object, _  8        ByVal e As System.EventArgs) Handles Me.Load  9        ' if this is not the first time the page is loading 10        ' (i.e., the user has already submitted form data) 11        If IsPostBack Then 12           ' retrieve the values submitted by the user 13           Dim name As String = Request.Form("nameTextBox") 14           Dim email As String = Request.Form("emailTextBox") 15           Dim phone As String = Request.Form("phoneTextBox") 16 17           ' create a table indicating the submitted values 18           outputLabel.Text &= _ 19              "<br />We received the following information:" & _ 20              "<table style=""background-color: yellow"">" & _ 21              "<tr><td>Name: </td><td>" & name & "</td></tr>" & _ 22              "<tr><td>E-mail address: </td><td>" & email & "</td></tr>" & _ 23              "<tr><td>Phone number: </td><td>" & phone & "</td></tr>" & _ 24              "<table>" 25           outputLabel.Visible = True ' display the output message 26        End If 27     End Sub ' Page_Load 28  End Class ' Validation 

Web programmers using ASP.NET often design their Web pages so that the current page reloads when the user submits the form; this enables the program to receive input, process it as necessary and display the results in the same page when it is loaded the second time. These pages usually contain a form that when submitted, sends the values of all the controls to the server and causes the current page to be requested again. This event is known as a postback. Line 11 uses the IsPostBack property of class Page to determine whether the page is being loaded due to a postback. The first time that the Web page is requested, IsPostBack is False, and the page displays only the form for user input. When the postback occurs (from the user clicking Submit), IsPostBack is true.

Lines 1315 use the Request object to retrieve the values of nameTextBox, emailTextBox and phoneTextBox from the NameValueCollection Form. When data is posted to the Web server, the XHTML form's data is accessible to the Web application through the Request object's Form array. Lines 1824 append to outputLabel's Text a line break, an additional message and an XHTML table containing the submitted data so the user knows that the server received the data correctly. In a real business application, the data would be stored in a database or file at this point in the application. Line 25 sets the outputLabel's Visible property to TRue, so the user can see the thank you message and submitted data.

Examining the Client-Side XHTML for a Web Form with Validation

Figure 21.22 shows the XHTML and ECMAScript sent to the client browser when Validation.aspx loads after the postback. (We added the comments in lines 12.) To view this code, select View > Source in Internet Explorer. Lines 2755, lines 126190 and lines 196212 contain the ECMAScript that provides the implementation for the validation controls and for performing the postback. ASP.NET generates this ECMAScript. You do not need to be able to create or even understand ECMAScriptthe functionality defined for the controls in our application is converted to working ECMAScript for us.

Figure 21.22. XHTML and ECMAScript generated by ASP.NET and sent to the browser when Validation.aspx is requested.

  1  <!-- Fig. 21.22 -->  2  <!-- The XHTML and ECMAScript generated for Validation.aspx -->  3  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  4     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  5  <html xmlns="http://www.w3.org/1999/xhtml" >  6  <head>  7  <title>Demonstrating Validation Controls</title>  8  </head>  9  <body> 10  <form name="form1" method="post" action="Validation.aspx" 11     onsubmit="javascript:return WebForm_OnSubmit();" id="form1"> 12     <div> 13        <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" 14           value="" /> 15        <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" 16           value= "" /> 17        <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"            18           value="/wEPDwUJMzg4NDI1NzgzD2QWAgIDD2QWAgITDw8WBB4EVGV4dAWVAlRoY 19           W5rIHlvdSBmb3IgeW91ciBzdWJtaXNzaW9uLjxiciAvPldlIHJlY2VpdmVkIHRoZ 20           SBmb2xsb3dpbmcgaW5mb3JtYXRpb246PHRhYmxlIHN0eWxlPSJiYWNrZ3JvdW5kL 21           WNvbG9yOiB5ZWxsb3ciPjx0cj48dGQ+TmFtZTogPC90ZD48dGQ+Qm9iIFdoaXRlP 22           C90ZD48L3RyPjx0cj48dGQ+RS1tYWlsIGFkZHJlc3M6IDwvdGQ+PHRkPmJ3aGl0  23           ZUBlbWFpbC5jb208L3RkPjwvdHI+PHRyPjx0ZD5QaG9uZSBudW1iZXI6IDwvdGQ+ 24           PHRkPig1NTUpIDU1NS0xMjM0PC90ZD48L3RyPjx0YWJsZT4eB1Zpc2libGVnZGRk 25           qbjgKg1/lLZfogqihtkd1C7nmSk=" />                                 26     </div> 27     <script type="text/javascript"> 28     <!-- 29     var theForm = document.forms['form1']; 30     if (!theForm) { 31        theForm = document.form1; 32     } 33     function __doPostBack(eventTarget, eventArgument) { 34        if (!theForm.onsubmit || (theForm.onsubmit() != false)) { 35           theForm.__EVENTTARGET.value = eventTarget; 36           theForm.__EVENTARGUMENT.value = eventArgument; 37           theForm.submit(); 38        } 39     } 40     // --> 41     </script> 42     <script src="/Validation/WebResource.axd?d=g4BXOwpt2-0jwFwNi7BCNQ2 43        &amp;t=632670465355304640" type="text/javascript"></script> 44     <script src="/Validation/WebResource.axd?d=ZlFGPYdc0paOPqraRf9s2PN8QeuH 45        PzQxnkR5mPVtAVc1&t=632670465355304640" 46        type="text/javascript"></script> 47     <script type="text/javascript"> 48     <!-- 49     function WebForm_OnSubmit() { 50        if (typeof(ValidatorOnSubmit) == "function" & & 51           ValidatorOnSubmit() == False) return false; 52        return true; 53     } 54     // --> 55     </script>$ 56     <div>$ 57        Please fill out the following form.<br /> 58        <em>All fields are required and must contain valid information. 59        </em><br /> 60        <br /> 61        <table> 62           <tr> 63              <td style="width: 100px" valign="top"> Name:</td> 64              <td style="width: 450px" valign="top"> 65                 <input name="nameTextBox" type="text" value="Bob White" 66                    id="nameTextBox" /> 67                 <br /> 68                 <span id="nameInputValidator" 69                   style="color:Red;display:none;"> 70                   Please enter your name.</span> </td> 71          </tr> 72          <tr> 73             <td style="width: 100px" valign="top">E-mail address:</td> 74             <td style="width: 450px" valign="top"> 75                <input name="emailTextBox" type="text" 76                   value="bwhite@email.com" id="emailTextBox" /> 77                &nbsp;e.g., user@domain.com<br /> 78                <span id="emailInputValidator" 79                   style="color:Red;display:none;"> 80                   Please enter your e-mail address. </span> 81                <span id="emailFormatValidator" 82                   style="color:Red;display:none;">Please enter an e-mail 83                   address in a valid format. </span> </td> 84          </tr> 85          <tr> 86             <td style="width: 100px; height: 21px" valign="top"> 87                Phone number: </td> 88             <td style="width: 450px; height: 21px" valign="top"> 89                <input name="phoneTextBox" type="text" 90                   value="(555) 555-1234" id="phoneTextBox" /> 91                 &nbsp;e.g., (555) 555-1234 <br /> 92                <span id= "phoneInputValidator" 93                   style= "color:Red;display:none;" > 94                   Please enter your phone number. </span> 95                <span id="phoneFormatValidator" 96                   style="color:Red;display:none;">Please enter a phone 97                   number in a valid format. </span> </td> 98           </tr> 99        </table> 100       <br /> 101       <input type="submit" name="submitButton" value="Submit" 102          onclick="javascript:WebForm_DoPostBackWithOptions( 103             new WebForm_PostBackOptions("submitButton", 104                &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, 105                false))" id="submitButton" /> 106       <br /> 107       <br /> 108       <span id="outputLabel">Thank you for your submission.<br /> 109          We received the following information: 110          <table style="background-color: yellow"> 111             <tr> 112                <td>Name: </td> 113                <td>Bob White </td> 114             </tr> 115             <tr> 116                <td>E-mail address: </td> 117                <td>bwhite@email.com</td> 118             </tr> 119             <tr> 120                <td>Phone number: </td> 121                <td>(555) 555-1234 </td> 122             </tr> 123          <table> 124       </span> 125    </div> 126    <script type="text/javascript"> 127    <!-- 128       var Page_Validators = new Array( 129          document.getElementById("nameInputValidator"), 130          document.getElementById("emailInputValidator"), 131          document.getElementById("emailFormatValidator"), 132          document.getElementById("phoneInputValidator"), 133          document.getElementById("phoneFormatValidator")); 134    // --> 135    </script> 136    <script type= "text/javascript"> 137    <!-- 138       var nameInputValidator = document.all ? 139          document.all[ "nameInputValidator" ] : 140          document.getElementById("nameInputValidator"); 141       nameInputValidator.controltovalidate = "nameTextBox"; 142       nameInputValidator.errormessage = "Please enter your name."; 143       nameInputValidator.display = "Dynamic"; 144       nameInputValidator.evaluationfunction = 145          "RequiredFieldValidatorEvaluateIsValid"; 146       nameInputValidator.initialvalue = ""; 147       var emailInputValidator = document.all ? 148          document.all[ "emailInputValidator" ] : 149          document.getElementById("emailInputValidator"); 150       emailInputValidator.controltovalidate = "emailTextBox"; 151       emailInputValidator.errormessage = 152          "Please enter your e-mail address."; 153       emailInputValidator.display = "Dynamic"; 154       emailInputValidator.evaluationfunction = 155          "RequiredFieldValidatorEvaluateIsValid"; 156       emailInputValidator.initialvalue = ""; 157       var emailFormatValidator = document.all ? 158          document.all[ "emailFormatValidator"] : 159          document.getElementById("emailFormatValidator";); 160       emailFormatValidator.controltovalidate = "emailTextBox"; 161       emailFormatValidator.errormessage = 162          "Please enter an e-mail address in a valid format."; 163       emailFormatValidator.display = "Dynamic"; 164       emailFormatValidator.evaluationfunction = 165          "RegularExpressionValidatorEvaluateIsValid"; 166       emailFormatValidator.validationexpression = 167          "\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; 168       var phoneInputValidator = document.all ? 169          document.all[ "phoneInputValidator"] : 170          document.getElementById("phoneInputValidator";) 171       phoneInputValidator.controltovalidate = "phoneTextBox"; 172       phoneInputValidator.errormessage = 173          "Please enter your phone number."; 174       phoneInputValidator.display = "Dynamic"; 175       phoneInputValidator.evaluationfunction = 176          "RequiredFieldValidatorEvaluateIsValid"; 177       phoneInputValidator.initialvalue = ""; 178       var phoneFormatValidator = document.all ? 179          document.all[ "phoneFormatValidator" ] : 180          document.getElementById("phoneFormatValidator";); 181       phoneFormatValidator.controltovalidate = "phoneTextBox"; 182       phoneFormatValidator.errormessage = 183          "Please enter a phone number in a valid format."; 184       phoneFormatValidator.display = "Dynamic"; 185       phoneFormatValidator.evaluationfunction = 186          "RegularExpressionValidatorEvaluateIsValid"; 187       phoneFormatValidator.validationexpression = 188          "((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}" ; 189     // --> 190     </script> 191     <div> 192        <input type= "hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" 193            value="/wEWBQL6jZCbCAKLsYSOBwKCkfPgDAKE8IO1CQKSuuDUC0eNO370TaQqZQ 194               0WPApD0KktGC5N" /> 195     </div> 196     <script type="text/javascript"> 197     <!-- 198        var Page_ValidationActive = False; 199        if (typeof(ValidatorOnLoad) == "function") { 200            ValidatorOnLoad(); 201        } 202 203        function ValidatorOnSubmit() { 204           if (Page_ValidationActive) { 205              return ValidatorCommonOnSubmit(); 206           } 207           else { 208             return true; 209           } 210        } 211     // --> 212     </script> 213  </form> 214  </body> 215  </html> 

The EnableViewState attribute determines whether a Web control's value is retained when a postback occurs. Previously, we explicitly set this attribute to False. The default value, true, indicates that the control's value is retained. In Fig. 21.20(d), notice that the user input is retained after the postback occurs. A hidden input in the XHTML document (lines 1725 of Fig. 21.22) contains the data of the controls on this page. This element is always named __VIEWSTATE and stores the controls' data as an encoded string.

Performance Tip 21.1

Setting EnableViewState to False reduces the amount of data passed to the Web server with each request.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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