Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Creating and Running a Simple Web Form Example - ASP.NET

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - ASP.NET 2.0 and ASP.NET Ajax

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Creating and Running a Simple Web Form Example - ASP.NET

Our 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.

Creating and Running a Simple Web Form Example


Our 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 files—an ASPX file (Fig. 25.1) and a Visual Basic code-behind file (Fig. 25.2), which we’ll discuss in Section 25.2.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. 25.1 and other ASPX file listings in this chapter is the same as the markup that appears in Visual Web Developer, but we’ve reformatted it for presentation purposes to make the code more readable.]


Visual Web Developer generates all the markup shown in Fig. 25.1 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 25.2.6.


1    <%-- Fig. 25.1: WebTime.aspx --%>


2    <%-- A page that displays the current time in a Label. --%>


3    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="WebTime.aspx.vb"


4          Inherits="WebTime" EnableSessionState="False" %>


6    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


7          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


9    <html xmlns="http://www.w3.org/1999/xhtml" >


10   <head runat="server">


11         <title>A Simple Web Form Example</title>


12   </head>


13   <body>


14         <form id="form1" runat="server">


15         <div>

16               <h2>


Current time on the Web server:</h2>

18                <p>


19                      <asp:Label ID="timeLabel" runat="server" BackColor="Black"

20     EnableViewState="False" Font-Size="XX-Large"

21                            ForeColor="Yellow"></asp:Label>

22                </p>


23         </div>


24         </form>


25   </body>


26   </html>


Fig. 25.1 | ASPX file that displays the web server’s time.


1. Examining an ASPX File


The ASPX file contains other information in addition to XHTML. Lines 1–2 are ASP.NET comments that indicate the figure number, the filename and the purpose of the file. ASP.NET comments begin with <%-- and terminate with --%>. We added these com-ments to the file. ASP.NET comments are not output as part of the XHTML sent to the client. Lines 3–4 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 at-tribute 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 filename (e.g., WebTime.aspx) followed by a filena-me extension indicating the programming language (.vb in this chapter’s examples).


The AutoEventWireup attribute (line 3) determines how Web Form events are han-dled. When AutoEventWireup is set to true, ASP.NET determines which methods in the class are called in response to events generated in 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. AutoEventWireup requires the event-handling methods to follow specific naming copnventions. (We discuss these events later in the chapter.)


The Inherits attribute (line 4) specifies the page’s class name—in this case, WebTime. We say more about Inherits momentarily. [Note: We explicitly set the EnableSession-State 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 capi-talization 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. For more information on XHTML, see Chapter 4. Lines 6–7 contain the document type dec-laration, which specifies the document element name (HTML) and the PUBLIC Uniform Resource Identifier (URI) for the DTD that defines the XHTML vocabulary.


Lines 9–10 contain the <html> and <head> start tags, respectively. XHTML docu-ments 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 docu-ment using the xmlns attribute (see Section 14.4).


Notice the runat attribute in line 10, which is set to "server". This attribute indi-cates 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 14–24. 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 15–23 contain a div element that groups the elements of the form in a block of markup.

Lines 16–17 are an XHTML h2 heading element. 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 18–22 contain a p element to mark up a paragraph of content in the browser. Lines 19–21 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 pro-grammatically 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 rep-resent that control in a web browser.

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 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 repre-sented as part of the style attribute of the span element. You will soon see what the gen-erated span element’s markup looks like.


The web control in this example contains the runat="server" attribute–value pair (line 19), because this control must be processed on the server so that the server can trans-late 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).


2. Examining a Code-Behind File


Figure 25.2 presents the code-behind file. Recall that the ASPX file in Fig. 25.1 references WebTime.aspx.vb in line 3.


Line 3 (Fig. 25.2) begins the declaration of class WebTime. A class declaration can span multiple source-code files, and 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 applica-tions. Class Page provides events and objects necessary for creating web-based applica-tions. In addition to class Page, System.Web.UI also includes class Control—the base class that provides common functionality for all web controls.


Lines 7–11 define method Page_Init, which handles the page’s Init event. This event indicates that all the controls on the page have been created and initialized and addi-tional application-specific initialization can now be performed. 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.


1    ' Fig. 25.5: WebTime.aspx.vb


2    ' Code-behind file for a page that displays the current time.


3    Partial Class WebTime


4          Inherits System.Web.UI.Page


6          ' initializes the contents of the page


7          Protected Sub Page_Init(ByVal sender As Object, _


8                 ByVal e As System.EventArgs) Handles Me.Init


9                 ' display the server's current time in timeLabel


10               timeLabel.Text = DateTime.Now.ToString("hh:mm:ss")


11         End Sub ' Page_Init


12   End Class ' WebTime



3. Relationship Between an ASPX File and a Code-Behind File


How 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. 25.1). This class (partially declared in the code-behind file) inherits from Page, which defines general web page functionality. Partial class WebTime inherits this function-ality 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 gen-erate 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 time-Label, 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 for displaying text. It is defined in namespace System.Web.UI.WebControls, which contains 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 com-plete WebTime class. This explains why line 10 in Fig. 25.2 can access timeLabel, which is created in lines 19–21 of WebTime.aspx (Fig. 25.1)—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. 25.2, 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 sub-directory of



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 the web page has been compiled, no recompilation is required on subsequent requeses. New instances of the web page class will be created to serve each request. 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.


4. How the Code in an ASP.NET Web Page Executes


Let’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, which 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 exe-cutes, 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 user’s request is considered fully processed, 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 re-sources used by the page. Other events occur as well, but are typically used only by ASP.NET controls to generate XHTML to render client-side controls. You can learn more about a Page’s event life cycle at msdn2.microsoft.com/en-US/library/ms178472.aspx.


5. Examining the XHTML Generated by an ASP.NET Application


Figure 25.3 shows the XHTML generated by ASP.NET when a client browser requests WebTime.aspx (Fig. 25.1). To view this code, select View > Source in Internet Explorer. We added the comments in lines 1–2 and reformatted the XHTML for readability.


The markup in this page is similar to the ASPX file. Lines 7–9 define a document header comparable to that in Fig. 25.1. Lines 10–25 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 pro-cessing; however, processing user data is a crucial part of many applications that is facili-tated 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 compo-nents, called hidden inputs, store data, such as e-mail addresses, that the document author specifies. A hidden input is defined in lines 13–14. We discuss the precise meaning of this


1    <!-- Fig. 25.3: WebTime.html -->


2    <!-- The XHTML generated when WebTime.aspx is loaded. -->


3    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"


4          "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">


6    <html xmlns="http://www.w3.org/1999/xhtml" >


7    <head>


8          <title>A Simple Web Form Example</title>


9    </head>


10   <body>


11         <form name="form1" method="post" action="WebTime.aspx" id="form1">


12                <div>


13                      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value=

14                            "/wEPDwUJODExMDE5NzY5ZGSzVbs789nqEeoNueQCnCJQEUgykw==" />


15                </div>


17                <div>


18                      <h2>Current time on the Web server:</h2>


<span id="timeLabel" style="color:Yellow;



22                      </p>


23                </div>


24         </form>


25   </body>


26   </html>


Fig. 25.3 | XHTML response when the browser requests WebTime.aspx.


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 submitted—in this case, WebTime.aspx. Recall that the ASPX file’s form element contained the runat="server" attribute–value pair (line 14 of Fig. 25.1). 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 20–21 of Fig. 25.3) 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" attribute–value 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.


6. Building an ASP.NET Web Application


Now 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.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.