21.4. Creating and Running a Simple Web-Form ExampleOur first example displays the Web server's time of day in a browser window. When run, this program displays the text A Simple Web Form Example, followed by the Web server's time. As mentioned previously, the program consists of two related filesan ASPX file (Fig. 21.4) and a Visual Basic code-behind file (Fig. 21.5). We first display the markup, code and output, then we carefully guide you through the step-by-step process of creating this program. [Note: The markup in Fig. 21.4 and other ASPX file listings in this chapter is the same as the markup that appears in Visual Web Developer, but we have reformatted the markup for presentation purposes to make the code more readable.] Figure 21.4. ASPX file that displays the Web server's time.
Figure 21.5. Code-behind file for a page that displays the Web server's time.
Visual Web Developer generates all the markup shown in Fig. 21.4 when you set the Web page's title, type text in the Web Form, drag a Label onto the Web Form and set the properties of the page's text and the Label. We discuss these steps in Section 21.4.6. 21.4.1. Examining an ASPX FileThe ASPX file contains other information in addition to XHTML. Lines 12 are ASP.NET comments that indicate the figure number, the file name and the purpose of the file. ASP.NET comments begin with <%-- and terminate with --%>. We added these comments to the file. Lines 34 use a Page directive (in an ASPX file a directive is delimited by <%@ and %>) to specify information needed by ASP.NET to process this file. The Language attribute of the Page directive specifies the language of the code-behind file as Visual Basic ("VB"); the code-behind file (i.e., the CodeFile) is WebTime.aspx.vb. A code-behind file name usually consists of the full ASPX file name (e.g., WebTime.aspx) followed by the .vb extension. The AutoEventWireup attribute (line 3) determines how Web Form events are handled. When AutoEventWireup is set to TRue, ASP.NET determines which methods in the class are called in response to an event generated by the Page. For example, ASP.NET will call methods Page_Init and Page_Load in the code-behind file to handle the Page's Init and Load events, respectively. (We discuss these events later in the chapter.) The Inherits attribute (line 4) specifies the page's class namein this case, WebTime. We say more about Inherits momentarily. [Note: We explicitly set the EnableSessionState attribute (line 4) to False. We explain the significance of this attribute later in the chapter. The IDE sometimes generates attribute values (e.g., TRue and false) and control names (as you will see later in the chapter) that do not adhere to our standard code capitalization conventions (i.e., true and False). Like Visual Basic, ASP.NET markup is not case-sensitive, so using a different case is not problematic. To remain consistent with the code generated by the IDE, we do not modify these values in our code listings or in our accompanying discussions.] For this first ASPX file, we provide a brief discussion of the XHTML markup. We do not discuss the majority of the XHTML contained in subsequent ASPX files. Lines 67 contain the document type declaration, which specifies the document element name (HTML) and the PUBLIC Uniform Resource Identifier (URI) for the DTD that defines the XHTML vocabulary. Lines 910 contain the <html> and <head> start tags, respectively. XHTML documents have the root element html and mark up information about the document in the head element. Also note that the html element specifies the XML namespace of the document using the xmlns attribute (see Section 19.4). Notice the runat attribute in line 10, which is set to "server". This attribute indicates that when a client requests this ASPX file, ASP.NET processes the head element and its nested elements on the server and generates the corresponding XHTML, which is then sent to the client. In this case, the XHTML sent to the client will be identical to the markup in the ASPX file. However, as you will see, ASP.NET can generate complex XHTML markup from simple elements in an ASPX file. Line 11 sets the title of this Web page. We demonstrate how to set the title through a property in the IDE shortly. Line 13 contains the <body> start tag, which begins the body of the XHTML document; the body contains the main content that the browser displays. The form that contains our XHTML text and controls is defined in lines 1424. Again, the runat attribute in the form element indicates that this element executes on the server, which generates equivalent XHTML and sends it to the client. Lines 1523 contain a div element that groups the elements of the form in a block of markup. Lines 1617 are an XHTML H2 heading element that contains text indicating the purpose of the Web page. As we demonstrate shortly, the IDE generates this element in response to typing text directly in the Web Form and selecting the text as a second-level heading. Lines 1822 contain a p element to mark up a paragraph of content in the browser. Lines 1921 mark up a label Web control. The properties that we set in the Properties window, such as Font-Size and BackColor (i.e., background color), are attributes here. The ID attribute (line 19) assigns a name to the control so that it can be manipulated programmatically in the code-behind file. We set the control's EnableViewState attribute (line 20) to False. We explain the significance of this attribute later in the chapter. The asp: tag prefix in the declaration of the Label tag (line 19) indicates that the label is an ASP.NET Web control, not an XHTML element. Each Web control maps to a corresponding XHTML element (or group of elements)when processing a Web control on the server, ASP.NET generates XHTML markup that will be sent to the client to represent that control in a Web browser. Portability Tip 21.1
In this example, the asp:Label control maps to the XHTML span element (i.e., ASP.NET creates a span element to represent this control in the client's Web browser). A span element contains text that is displayed in a Web page. This particular element is used because span elements allow formatting styles to be applied to text. Several of the property values that were applied to our label are represented as part of the style attribute of the span element. You will soon see what the generated span element's markup looks like. The Web control in this example contains the runat="server" attributevalue pair (line 19), because this control must be processed on the server so that the server can translate the control into XHTML that can be rendered in the client browser. If this attribute pair is not present, the asp:Label element is written as text to the client (i.e., the control is not converted into a span element and does not render properly). 21.4.2. Examining a Code-Behind FileFig. 21.5 presents the code-behind file. Recall that the ASPX file in Fig. 21.4 references this file in line 3. Line 3 begins the declaration of class WebTime. Recall from Section 9.6 that a class declaration can span multiple source-code files and that the separate portions of the class declaration in each file are known as partial classes. The Partial modifier in line 3 indicates that the code-behind file is a partial class. We discuss the remainder of this class shortly. Line 4 indicates that WebTime inherits from class Page in namespace System.Web.UI. This namespace contains classes and controls that assist in building Web-based applications. Class Page provides event handlers and objects necessary for creating Web-based applications. In addition to class Page (from which all Web applications directly or indirectly inherit), System.Web.UI also includes class Controlthe base class that provides common functionality for all Web controls. Lines 711 define method Page_Init, which handles the page's Init event. This event indicates that the page is ready to be initialized. The only initialization required for this page is setting timeLabel's Text property to the time on the server (i.e., the computer on which this code executes). The statement in line 10 retrieves the current time and formats it as hh:mm:ss. For example, 9 AM is formatted as 09:00:00, and 2:30 PM is formatted as 14:30:00. Notice that the code-behind file can access timeLabel (the ID of the Label in the ASPX file) programmatically, even though the file does not contain a declaration for a variable named timeLabel. You will learn why momentarily. 21.4.3. Relationship Between an ASPX File and a Code-Behind FileHow are the ASPX and code-behind files used to create the Web page that is sent to the client? First, recall that class WebTime is the base class specified in line 4 of the ASPX file (Fig. 21.4). This class (partially declared in the code-behind file) inherits from Page, which defines general Web page functionality. Partial class WebTime inherits this functionality and defines some of its own (i.e., displaying the current time). The code in the code-behind file displays the time, whereas the code in the ASPX file defines the GUI. When a client requests an ASPX file, ASP.NET creates two partial classes behind the scenes. The code-behind file contains one partial class named WebTime and ASP.NET generate another partial class containing the remainder of class WebTime, based on the markup in the ASPX file. For example, WebTime.aspx contains a Label Web control with ID timeLabel, so the generated partial class would contain a declaration for a variable named timeLabel of type System.Web.UI.WebControls.Label. Class Label represents a Web control defined in namespace System.Web.UI.WebControls, which contains various Web controls for designing a page's user interface. Web controls in this namespace derive from class WebControl. When compiled, the partial class that declares timeLabel combines with the code-behind file's partial class declaration to form the complete WebTime class. This explains why line 10 in Fig. 21.5 can access timeLabel, which is created in lines 1921 of WebTime.aspx (Fig. 21.4)method Page_Init and control timeLabel are actually members of the same class, but defined in separate partial classes. The partial class generated by ASP.NET is based on the ASPX file that defines the page's visual representation. This partial class is combined with the one in Fig. 21.5, which defines the page's logic. The first time the Web page is requested, this class is compiled and an instance is created. This instance represents the page and creates the XHTML that is sent to the client. The assembly created from the compiled partial classes is placed in a subdirectory of C:\WINDOWS\Microsoft.NET\Framework\VersionNumber\ Temporary ASP.NET Files\WebTime where VersionNumber is the version number of the .NET Framework (e.g., v2.0.50727) installed on your computer. Once an instance of the Web page has been created, multiple clients can use it to access the pageno recompilation is necessary. The project will be recompiled only when you modify the application; changes are detected by the runtime environment, and the application is recompiled to reflect the altered content. 21.4.4. How the Code in an ASP.NET Web Page ExecutesLet's look briefly at how the code for our Web page executes. When an instance of the page is created, the PreInit event occurs first, invoking method Page_PreInit. Method Page_PreInit can be used to set a page's theme and look-and-feel (and perform other tasks that are beyond this chapter's scope). The Init event occurs next, invoking method Page_Init. Method Page_Init is used to initialize objects and other aspects of the page. After Page_Init executes, the Load event occurs, and the Page_Load event handler executes. Although not present in this example, the PreInit and Load events are inherited from class Page. You will see examples of the Page_Load event handler later in the chapter. After the Load event handler finishes executing, the page processes events that are generated by the page's controls, such as user interactions with the GUI. When the Web Form object is ready for garbage collection, an Unload event occurs, which calls the Page_Unload event handler. This event, too, is inherited from class Page. Page_Unload typically contains code that releases resources used by the page. Other events occur as well, but are typically used only by ASP.NET controls to render themselves. You can learn more about a Page's event lifecycle at msdn2.microsoft.com/en-US/library/ms178472.aspx. 21.4.5. Examining the XHTML Generated by an ASP.NET ApplicationFig. 21.6 shows the XHTML generated by ASP.NET when a client browser requests WebTime.aspx (Fig. 21.4). To view this code, select View > Source in Internet Explorer. We added the comments in lines 12 and reformatted the XHTML for readability. Figure 21.6. XHTML response when the browser requests WebTime.aspx.
The markup in this page is similar to the ASPX file. Lines 79 define a document header comparable to that in Fig. 21.4. Lines 1025 define the document's body. Line 11 begins the form, a mechanism for collecting user information and sending it to the Web server. In this particular program, the user does not submit data to the Web server for processing; however, processing user data is a crucial part of many applications that is facilitated by forms. We demonstrate how to submit form data to the server in later examples. XHTML forms can contain visual and nonvisual components. Visual components include buttons and other GUI components with which users interact. Nonvisual components, called hidden inputs, store data, such as e-mail addresses, that the document author specifies. A hidden input is defined in lines 1314. We discuss the precise meaning of this hidden input later in the chapter. Attribute method of the form element (line 11) specifies the method by which the Web browser submits the form to the server. The action attribute identifies the name and location of the resource that will be requested when this form is submittedin this case, WebTime.aspx. Recall that the ASPX file's form element contained the runat="server" attributevalue pair (line 14 of Fig. 21.4). When the form is processed on the server, the runat attribute is removed. The method and action attributes are added, and the resulting XHTML form is sent to the client browser. In the ASPX file, the form's Label (i.e., timeLabel) is a Web control. Here, we are viewing the XHTML created by our application, so the form contains a span element (lines 2021 of Fig. 21.6) to represent the text in the label. In this particular case, ASP.NET maps the Label Web control to an XHTML span element. The formatting options that were specified as properties of timeLabel, such as the font size and color of the text in the Label, are now specified in the style attribute of the span element. Notice that only those elements in the ASPX file marked with the runat="server" attributevalue pair or specified as Web controls are modified or replaced when the file is processed by the server. The pure XHTML elements, such as the H2 in line 18, are sent to the browser as they appear in the ASPX file. 21.4.6. Building an ASP.NET Web ApplicationNow that we have presented the ASPX file, the code-behind file and the resulting Web page sent to the Web browser, we show the steps we used to create this application in Visual Web Developer.
If you created the ASP.NET application on the local file system, the URL shown in the browser will be http://localhost:PortNumber/WebTime/WebTime.aspx, where PortNumber is the number of the randomly assigned port on which Visual Web Developer's built-in test server runs. The IDE assigns the port number on a per solution basis. This URL indicates that the WebTime project folder is being accessed through the root directory of the test server running at localhost:PortNumber. When you select Debug > Start Without Debugging, a tray icon appears near the bottom-right of your screen next to the computer's date and time to show that the ASP.NET Development Server is running. The test server stops when you exit Visual Web Developer. To debug your application, you can select Debug > Start Debugging to view the Web page in a Web browser with debugging enabled. You cannot debug a Web application unless debugging is explicitly enabled by the Web.config filea file that stores configuration settings for an ASP.NET Web application. You will rarely need to manually create or modify Web.config. The first time you select Debug > Start Debugging in a project, a dialog appears and asks whether you want the IDE to modify the Web.config file to enable debugging. After you click OK, the IDE enters Running mode. You can exit Running mode by selecting Debug > Stop Debugging in Visual Web Developer or by closing the browser window in which the ASPX file is displayed. To view a specific ASPX file, you can right click either the Web Forms Designer or the ASPX file name (in the Solution Explorer) and select View In Browser to load the page in a Web browser. Right clicking the ASPX file in the Solution Explorer and selecting Browse With… also opens the page in a browser, but first allows you to specify the Web browser that should display the page and its screen resolution. Finally, you can run your application by opening a browser window and typing the Web page's URL in the Address field. When testing an ASP.NET application on the same computer running IIS, type http://localhost/ProjectFolder/PageName.aspx, where ProjectFolder is the folder in which the page resides (usually the name of the project), and PageName is the name of the ASP.NET page. If your application resides on the local file system, you must first start the ASP.NET Development Server by running the application using one of the methods described above. Then you can type the URL (including the PortNumber found in the test server's tray icon) in the browser to execute the application. Note that all of these methods of running the application compile the project for you. In fact, ASP.NET compiles your Web page whenever it changes between HTTP requests. For example, suppose you browse the page, then modify the ASPX file or add code to the code-behind file. When you reload the page, ASP.NET recompiles the page on the server before returning the HTTP response to the browser. This important new behavior of ASP.NET 2.0 ensures that clients always see the latest version of the page. You can manually compile a Web page or an entire Web site by selecting Build Page or Build Site, respectively, from the Build menu in Visual Web Developer. Windows Firewall SettingsIf you would like to test your Web application over a network, you may need to change your Windows Firewall settings. For security reasons, Windows Firewall does not allow remote access to a Web server on your local computer by default. To change this, open the Windows Firewall utility in the Windows Control Panel. Click the Advanced tab and select your network connection from the Network Connection Settings list, then click Settings…. On the Services tab of the Advanced Settings dialog, ensure that Web Server (HTTP) is checked. |