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. Note that all the code in Fig. 21.16 was generated by Visual Web Developer in response to actions performed in Design mode. [Note: This example does not contain any functionalityi.e., no action occurs when the user clicks Register. We ask the reader to provide the functionality as an exercise. In successive 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="C#" AutoEventWireup="true" 4 CodeFile="WebControls.aspx.cs" Inherits="WebControls" 5 EnableSessionState="False" %> 6 7 "-//W3C//DTD XHTML 1.1//EN" 8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 9 10

"http://www.w3.org/1999/xhtml"> 11 "server"> 12 Web Controls Demonstration 13 14 15 "form1" runat="server"> 16 17

This is a sample registration form.

18

Please fill in all fields and click Register.

19

20 "UserInformationImage" runat="server" 21 ImageUrl="~/Images/user.png" EnableViewState="False" /> 22   23 "color: teal"> 24 Please fill out the fields below. 25

26 27283542 4344515960
"width: 230px; height: 21px" valign="top"> 29 "FirstNameImage" runat="server" 30 ImageUrl="~/Images/fname.png" 31 EnableViewState="False" /> 32 "FirstNameTextBox" runat="server" 33 EnableViewState="False"> 34 "width: 231px; height: 21px" valign="top"> 36 "LastNameImage" runat="server" 37 ImageUrl="~/Images/lname.png" 38 EnableViewState="False" /> 39 "LastNameTextBox" runat="server" 40 EnableViewState="False"> 41
"width: 230px" valign="top"> 45 "EmailImage" runat="server" 46 ImageUrl="~/Images/email.png" 47 EnableViewState="False" /> 48 "EmailTextBox" runat="server" 49 EnableViewState="False"> 50 "width: 231px" valign="top"> 52 "PhoneImage" runat="server" 53 ImageUrl="~/Images/phone.png" 54 EnableViewState="False" /> 55 "PhoneTextBox" runat="server" 56 EnableViewState="False">

57 Must be in the form (555) 555-5555. 58

61

62 "PublicationsImage" runat="server" 63 ImageUrl="~/Images/publications.png" 64 EnableViewState="False" /> 65   66 "color: teal"> 67 Which book would you like information about? 68

69

70 "BooksDropDownList" runat="server" 71 EnableViewState="False"> 72 Visual Basic 2005 How to Program 3e 73 74 Visual C# 2005 How to Program 2e 75 76 Java How to Program 6e 77 C++ How to Program 5e 78 XML How to Program 1e 79 80

81

82 "BooksHyperLink" runat="server" 83 NavigateUrl="http://www.deitel.com" Target="_blank" 84 EnableViewState="False"> 85 Click here to view more information about our books 86 87

88

89 "OSImage" runat="server" 90 ImageUrl="~/Images/os.png" EnableViewState="False" /> 91   92 "color: teal"> 93 Which operating system are you using? 94

95

96 "OperatingSystemRadioButtonList" 97 runat="server" EnableViewState="False"> 98 Windows XP 99 Windows 2000 100 Windows NT 101 Linux 102 Other 103 104

105

106 "RegisterButton" runat="server" 107 Text="Register" EnableViewState="False" /> 108

109 110 111 112

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 17), 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 2660) 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, make sure the Custom radio button is selected. In the Layout group box, change the values of the Rows and Columns combo boxes 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 from the palette shown. Click OK to apply the color. Note that the IDE places the colored text in an XHTML span element (e.g., lines 2324) 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/csharpforprogrammers2. 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 Add Folder > Regular 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.

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:InetpubwwwrootWebControls).

Lines 2660 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 3233 define a TextBox control used to collect the user's first name.

Lines 7079 define a DropDownList. This control is similar to the ComboBox Windows 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 7278). 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. It can also be accessed using the DropDownList Tasks menu, which is opened 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 performing 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 8286 of Fig. 21.16) adds a hyperlink to a Web page. The NavigateUrl property (line 83) 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 96103 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 106107). Like a Button Windows control, a Button Web control represents a button that triggers an action when clicked. A Button Web control typically maps to an input XHTML 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, the AdRotator control 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="C#" AutoEventWireup="true" 4 CodeFile="FlagRotator.aspx.cs" Inherits="FlagRotator" 5 EnableSessionState="False" %> 6 7 "-//W3C//DTD XHTML 1.1//EN" 8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 9 10

"http://www.w3.org/1999/xhtml" > 11 "server"> 12 Flag Rotator 13 14 "Images/background.png"> 15 "form1" runat="server"> 16 17

AdRotator Example

18

19 "countryRotator" runat="server" 20 DataSourceID="adXmlDataSource" 21 EnableViewState="False" /> 22 "adXmlDataSource" runat="server" 23 DataFile="~/App_Data/AdRotatorInformation.xml"> 24 25

26 27 28 29

(a)

(b)

(c)

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 (i.e., the h3 element in line 17) and one AdRotator control named countryRotator (lines 1921). This page also contains an XmlDataSource control (lines 2224), which supplies the data to the AdRotator control. The background attribute of the page's body element (line 14) is set to display 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 browse for background.png.

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 Fig. 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.)

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 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 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. File containing advertisement information used in AdRotator example.

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

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). 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. ECMAScript is typically executed on the client. Some clients do not support scripting or disable scripting. However, for security reasons, validation is always performed on the serverwhether or not the script executes 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 a in 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 5657 define TextBoxes for retrieving the user's name, e-mail address and phone number, respectively, and line 75 defines a Submit button. Lines 7779 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, 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="C#" AutoEventWireup="true" 4 CodeFile="Validation.aspx.cs" Inherits="Validation" %> 5 6 "-//W3C//DTD XHTML 1.1//EN" 7 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 8 9

"http://www.w3.org/1999/xhtml" > 10 "server"> 11 Demonstrating Validation Controls 12 13 14 "form1" runat="server"> 15 16 Please fill out the following form.

17 All fields are required and must 18 contain valid information.

19

20 2122 2331323335525354557273

"width: 100px" valign="top">Name: "width: 450px" valign="top"> 24 "nameTextBox" runat="server"> 25

26 "nameInputValidator" 27 runat="server" ControlToValidate="nameTextBox" 28 ErrorMessage="Please enter your name." 29 Display="Dynamic"> 30

"width: 100px" valign="top"> 34 E-mail address: "width: 450px" valign="top"> 36 "emailTextBox" runat="server"> 37 38  e.g., user@domain.com

39 "emailInputValidator" 40 runat="server" ControlToValidate="emailTextBox" 41 ErrorMessage="Please enter your e-mail address." 42 Display="Dynamic"> 43 44 ID="emailFormatValidator" runat="server" 45 ControlToValidate="emailTextBox" 46 ErrorMessage="Please enter an e-mail address in a 47 valid format." Display="Dynamic" 48 ValidationExpression= 49 "w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*"> 50 51

"width: 100px" valign="top">Phone number: "width: 450px" valign="top"> 56 "phoneTextBox" runat="server"> 57 58  e.g., (555) 555-1234

59 "phoneInputValidator" 60 runat="server" ControlToValidate="phoneTextBox" 61 ErrorMessage="Please enter your phone number." 62 Display="Dynamic"> 63 64 ID="phoneFormatValidator" runat="server" 65 ControlToValidate="phoneTextBox" 66 ErrorMessage="Please enter a phone number in a 67 valid format." Display="Dynamic" 68 ValidationExpression= 69 "(((d{3}) ?)|(d{3}-))?d{3}-d{4}"> 70 71

74 75 "submitButton" runat="server" Text="Submit" /> 76

77 "outputLabel" runat="server" 78 Text="Thank you for your submission." 79 Visible="False"> 80 81 82 83

(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 2629 define RequiredFieldValidator nameInputValidator, which confirms that nameTextBox is not empty. Line 27 associates nameTextBox with nameInputValidator by setting the validator's ControlToValidate property to nameTextBox. This indicates that nameInputValidator verifies the nameTextBox's contents. Property ErrorMessage's text (line 28) 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 control's Display property to Dynamic (line 29), the validator takes up space on the Web Form only when validation failsspace 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 4350 create a RegularExpressionValidator named emailFormatValidator. Line 45 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, bobwhite@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 6370) 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 7779).

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.cs 2 // Code-behind file for the form demonstrating validation controls. 3 using System; 4 using System.Data; 5 using System.Configuration; 6 using System.Web; 7 using System.Web.Security; 8 using System.Web.UI; 9 using System.Web.UI.WebControls; 10 using System.Web.UI.WebControls.WebParts; 11 using System.Web.UI.HtmlControls; 12 13 public partial class Validation : System.Web.UI.Page 14 { 15 // Page_Load event handler executes when the page is loaded 16 protected void Page_Load( object sender, EventArgs e ) 17 { 18 // if this is not the first time the page is loading 19 // (i.e., the user has already submitted form data) 20 if ( IsPostBack ) 21 { 22 // retrieve the values submitted by the user 23 string name = Request.Form[ "nameTextBox" ]; 24 string email = Request.Form[ "emailTextBox" ]; 25 string phone = Request.Form[ "phoneTextBox" ]; 26 27 // create a table indicating the submitted values 28 outputLabel.Text += 29 " We received the following information:" + 30 "" + 31"" + 32"" + 33"" + 34"

Name: " + name + "
E-mail address: " + email + "
Phone number: " + phone + "
"; 3536 outputLabel.Visible = true; // display the output message37 } // end if38 } // end method Page_Load39 } // 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 20 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 2325 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 2834 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 36 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. To view this code, select View > Source in Internet Explorer. Lines 2536, lines 100171 and lines 180218 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 2 3 "-//W3C//DTD XHTML 1.1//EN" 4 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 5 6

"http://www.w3.org/1999/xhtml" > 7 8 Demonstrating Validation Controls 9 10 11 "post" action="Validation.aspx" 12 onsubmit="javascript:return WebForm_OnSubmit();" id="form1"> 13

14 "hidden" name="__VIEWSTATE" id="__VIEWSTATE" 15 value="/wEPDwUJODc5MTExMzA4D2QWAgIDD2QWAgITDw8WBB4EVGV4dAWQ 16 AlRoYW5rIHlvdSBmb3IgeW91ciBzdWJtaXNzaW9uLjxiciAvPldlIHJlY2V 17 pdmVkIHRoZSBmb2xsb3dpbmcgaW5mb3JtYXRpb246PHRhYmxlIHN0eWxlPS 18 JiYWNrZ3JvdW5kLWNvbG9yOiB5ZWxsb3ciPjx0cj48dGQ+TmFtZTogPC90Z 19 D48dGQ+Qm9iPC90ZD48L3RyPjx0cj48dGQ+RS1tYWlsIGFkZHJlc3M6IDwv 20 dGQ+PHRkPmJ3aGl0ZUBlbWFpbC5jb208L3RkPjwvdHI+PHRyPjx0ZD5QaG9 21 uZSBudW1iZXI6IDwvdGQ+PHRkPig1NTUpIDU1NS0xMjM0PC90ZD48L3RyPj 22 wvdGFibGU+HgdWaXNpYmxlZ2RkZHiyTaX3DhELahxLUxCHnaZuvuMd" /> 23

24 25 28 29 37 38 39 Please fill out the following form.

40 All fields are required and must 41 contain valid information.

42

43 44454652535456676869708182

"width: 100px" valign="top">Name: "width: 450px" valign="top"> 47 "nameTextBox" type="text" 48 id="nameTextBox" />

49 "nameInputValidator" style="color:Red; 50 display:none;">Please enter your name. 51

"width: 100px" valign="top"> 55 E-mail address: "width: 450px" valign="top"> 57 "emailTextBox" type="text" 58 id="emailTextBox" /> 59  e.g., user@domain.com

60 "emailInputValidator" style="color:Red; 61 display:none;">Please enter your e-mail address. 62 63 "emailFormatValidator" style="color:Red; 64 display:none;">Please enter an e-mail address in a 65 valid format. 66

"width: 100px" valign="top">Phone number: "width: 450px" valign="top"> 71 "phoneTextBox" type="text" 72 id="phoneTextBox" /> 73  e.g., (555) 555-1234

74 "phoneInputValidator" style="color:Red; 75 display:none;">Please enter your phone number. 76 77 "phoneFormatValidator" style="color:Red; 78 display:none;">Please enter a phone number in a 79 valid format. 80

83

84 "submit" name="submitButton" value="Submit" 85 onclick="javascript:WebForm_DoPostBackWithOptions( 86 new WebForm_PostBackOptions("submitButton", 87 "", true, "", "", 88 false, false))" id="submitButton" /> 89

90 "outputLabel">Thank you for your submission.

91 We received the following information: 92 "background-color: yellow">93949596

Name: Bob
E-mail address: bwhite@email.com
Phone number: (555) 555-1234
97 98 99 100 110 111 172 173

174 "hidden" name="__EVENTTARGET" 175 id="__EVENTTARGET" value="" /> 176 "hidden" name="__EVENTARGUMENT" 177 id="__EVENTARGUMENT" value="" /> 178

179 180 197 198 200 201 219 220 221

In earlier ASPX files, we explicitly set the EnableViewState attribute of each Web control to False. This attribute determines whether a Web control's value persists (i.e., is retained) when a postback occurs. By default, this attribute is true, which indicates that the control's value persists. In Fig. 21.20(d), notice that the values entered by the user still appear in the text boxes after the postback occurs. A hidden input in the XHTML document (lines 1422 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 2

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

Категории