Home > Articles > Programming > ASP .NET

This chapter is from the book

Web Forms Architecture

A Web Form consists of two parts:

  • The visual content or presentation, typically specified by HTML elements.

  • Code that contains the logic for interacting with the visual elements.

A Web Form is physically expressed by a file with the extension .aspx. Any HTML page could be renamed to have this extension and could be accessed using the new extension with identical results to the original. Thus Web Forms are upwardly compatible with HTML pages.

The way code can be separated from the form is what makes a Web Form special. This code can be either in a separate file (having an extension corresponding to a .NET language, such as .vb for VB.NET) or in the .aspx file, within a <SCRIPT RUNAT="SERVER"> ... /SCRIPT> block. When your page is run in the Web server, the user interface code runs and dynamically generates the output for the page.

We can understand the architecture of a Web Form most clearly by looking at the code-behind version of our "Echo" example. The visual content is specified by the .aspx file HelloCodebehind.aspx.

<!-- HelloCodebehind.aspx -->
<%@ Page Language="VB#" Src="HelloCodebehind.aspx.vb"
Inherits= MyWebPage %>
<HTML>
   <HEAD>
   </HEAD>
<BODY>
<FORM RUNAT="SERVER">YOUR NAME:&nbsp;
<asp:textbox id=txtName Runat="server"></asp:textbox>
<p><asp:button id=cmdEcho onclick=cmdEcho_Click Text="Echo"
   runat="server" tooltip="Click to echo your name">
</asp:button></p>
<asp:label id=lblGreeting runat="server"></asp:label>
<P></P>
</FORM>
</BODY>
</HTML>

The user interface code is in the file HelloCodebehind.aspx.vb,

' HelloCodebehind.aspx.vb

Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Class MyWebPage

       Inherits System.Web.UI.Page

       Protected txtName As TextBox
       Protected cmdEcho As Button
       Protected lblGreeting As Label

       Protected Sub cmdEcho_Click(Source As Object, _
         e As EventArgs)
            lblGreeting.Text="Hello, " & txtName.Text
       End Sub
End Class

Page Class

The key namespace for Web Forms and Web services is System.Web. Support for Web Forms is in the namespace System.Web.UI. Support for server controls such as textboxes and buttons is in the namespace Sys-tem.Web.UI.WebControls. The class that dynamically generates the output for an .aspx page is the Page class, in the System.Web.UI namespace, and classes derived from Page, as illustrated in the code-behind page in this last example.

INHERITING FROM PAGE CLASS

The elements in the .aspx file, the code in the code-behind file (or script block), and the base Page class work together to generate the page output. This cooperation is achieved by ASP.NET's dynamically creating a class for the .aspx file, which is derived from the code-behind class, which in turn is derived from Page. This relationship is created by the Inherits attribute in the .aspx file. Figure 14–6 illustrates the inheritance hierarchy. Here MyWebPage is a class we implement, derived from Page.

The most derived page class, shown as My .aspx Page in Figure 14–6, is dynamically created by the ASP.NET runtime. This class extends the page class, shown as MyWebPage in the figure, to incorporate the controls and HTML text on the Web Form. This class is compiled into an executable, which is run when the page is requested from a browser. The executable code creates the HTML that is sent to the browser.

Figure 14-6FIGURE 14–6 Hierarchy of page classes.

Web Forms Page Life Cycle

We can get a good high-level understanding of the Web Forms architecture by following the life cycle of our simple Echo application. We will use the code-behind version (the second example), HelloCodebehind.aspx.

  1. User requests the HelloCodebehind.aspx Web page in the browser.

  2. Web server compiles the page class from the .aspx file and its associated code-behind page. The Web server executes the code, creating HTML, which is sent to the browser. (In Internet Explorer you can see the HTML code from the menu View | Source.) Note that the server controls are replaced by straight HTML. The following code is what arrives at the browser, not the original code on the server.

  3. <!-- HelloCodebehind.aspx -->
    
    <HTML>
         <HEAD>
         </HEAD>
    <BODY>
    <form name="ctrl0" method="post"
    action="HelloCodebehind.aspx" id="ctrl0">
    value="dDwxMzc4MDMwNTk1Ozs+" />
    YOUR NAME:&nbsp; <input name="txtName" type="text"
    id="txtName" />
    <p><input type="submit" name="cmdEcho" value="Echo"
    id="cmdEcho" title="Click to echo your name" /></p>
         <span id="lblGreeting"></span>
    <P></P>
    </form>
    </BODY>
    </HTML>
  4. The browser renders the HTML, displaying the simple form shown in Figure 14–7. To distinguish this example from the first one, we show "YOUR NAME" in all capitals. Since this is the first time the form is displayed, the text box is empty, and no greeting message is displayed.

    Figure 14-7Figure 14-7 The form for the Echo application is diplayed for the first time.

  5. The user types in a name (e.g., Mary Smith) and clicks the Echo button. The browser recognizes that a Submit button has been clicked. The method for the form is POST1 and the action is HelloCodebehind.aspx. We thus have what is called a postback to the original .aspx file.

  6. The server now performs processing for this page. An event was raised when the user clicked the Echo button, and an event handler in the MyWebPage class is invoked.

    Protected Sub cmdEcho_Click(Source As Object, _
      e As EventArgs)
        lblGreeting.Text="Hello, " & txtName.Text
    End Sub
  7. The Text property of the TextBox server control txtName is used to read the name submitted by the user. A greeting string is composed and assigned to the Label control lblGreeting, again using property notation.

  8. The server again generates straight HTML for the server controls and sends the whole response to the browser. Here is the HTML.

  9. ...
    <form name="ctrl0" method="post"
    action="HelloCodebehind.aspx" id="ctrl0">
    <input type="hidden" name="__VIEWSTATE"
    value="dDwxMzc4MDMwNTk1O3Q8O2w8aTwyPjs+O2w8dDw7bDxpPDU+Oz47
    bDx0PHA8cDxsPFRleHQ7PjtsPEhlbGxvLCBNYXJ5IFNtaXRoOz4+Oz47Oz4
    7Pj47Pj47Pg==" />
    YOUR NAME:&nbsp; <input name="txtName" type="text"
    value="Mary Smith" id="txtName" />
    <p><input type="submit" name="cmdEcho" value="Echo"
    id="cmdEcho" title="Click to echo your name" /></p>
         <span id="lblGreeting">Hello, Mary Smith</span>
    ...
  10. The browser renders the page, as shown in Figure 14–8. Now a greeting message is displayed.

    Figure 14-8Figure 14-8 After a round trip, a greeting message is displayed.

View State

An important characteristic of Web Forms is that all information on forms is "remembered" by the Web server. Since HTTP is a stateless protocol, this preservation of state does not happen automatically but must be programmed. A nice feature of ASP.NET is that this state information, referred to as "view state," is preserved automatically by the framework, using a "hidden" control.

...
<input type="hidden" name="__VIEWSTATE"
value="dDwxMzc4MDMwNTk1O3Q8O2w8aTwyPjs+O2w8dDw7bDxpPDU+Oz47
bDx0PHA8cDxsPFRleHQ7PjtsPEhlbGxvLCBNYXJ5IFNtaXRoOz4+Oz47Oz4
7Pj47Pj47Pg==" />
...

Later in the chapter we will examine other facilities provided by ASP.NET for managing session state and application state.

Web Forms Event Model

From the standpoint of the programmer, the event model for Web Forms is very similar to the event model for Windows Forms. Indeed, this similarity is what makes programming with Web Forms so easy. What is actually happening in the case of Web Forms, though, is rather different. The big difference is that events get raised on the client and processed on the server.2 Our simple form with one textbox and one button is not rich enough to illustrate event processing very thoroughly. Let's imagine a more elaborate form with several textboxes, listboxes, checkboxes, buttons, and the like. Because round trips to the server are expensive, events do not automatically cause a postback to the server. Server controls have what is known as an intrinsic event set of events that automatically cause a postback to the server. The most common such intrinsic event is a button click. Other events, such as selecting an item in a list box, do not cause an immediate postback to the server. Instead, these events are cached, until a button click causes a post to the server. Then, on the server the various change events are processed, in no particular order, and the button-click event that caused the post is processed.

Page Processing

Processing a page is a cooperative endeavor between the Web server, the ASP.NET runtime, and your own code. The Page class provides a number of events, which you can handle to hook into page processing. The Page class also has properties and methods that you can use. We cover some of the major ones here. For a complete description, consult the .NET Framework documentation. The example programs in this chapter will illustrate features of the Page class.

PAGE EVENTS

A number of events are raised on the server as part of the normal processing of a page. These events are actually defined in the Control base class and so are available to server controls also. The most important ones are listed below.

  • Init is the first step in the page's life cycle and occurs when the page is initialized. There is no view-state information for any of the controls at this point.

  • Load occurs when the controls are loaded into the page. View-state information for the controls is now available.

  • PreRender occurs just before the controls are rendered to the output stream. Normally this event is not handled by a page but is important for implementing your own server controls.

  • Unload occurs when the controls are unloaded from the page. At this point it is too late to write your own data to the output stream.

PAGE PROPERTIES

The Page class has a number of important properties. Some of the most useful are listed below.

  • EnableViewState indicates whether the page maintains view state for itself and its controls. You can get or set this property. The default is true, view state is maintained.

  • ErrorPage specifies the error page to which the browser should be redirected in case an unhandled exception occurs.

  • IsPostBack indicates whether the page is being loaded in response to a postback from the client or is being loaded for the first time.

  • IsValid indicates whether page validation succeeded.3

  • Request gets the HTTP Request object, which allows you to access data from incoming HTTP requests.

  • Response gets the HTTP Response object, which allows you to send response data to a browser.

  • Session gets the current Session object, which is provided by ASP.NET for storing session state.

  • Trace gets a TraceContext object for the page, which you can use to write out trace information.

SAMPLE PROGRAM

We can illustrate some of these features of page processing with a simple extension to our Echo program. The page HelloPage.aspx (located in the top-level chapter directory) provides handlers for a number of page events, and we write simple text to the output stream, using the Response property. For each event we show the current text in the txtName and lblGreeting server controls. In the handler for Load we also show the current value of IsPostBack, which should be false the first time the page is accessed, and subsequently true.

<!-- HelloPage.aspx -->
<%@ Page Language="VB" Debug="true" %>
<HTML>
<HEAD>
   <SCRIPT RUNAT="SERVER">
Sub cmdEcho_Click(Source As Object, e As EventArgs)
      lblGreeting.Text="Hello, " & txtName.Text
End Sub

Sub Page_Init(sender As Object, E As EventArgs)
     Response.Write("Page_Init<br>")
     Response.Write("txtName = " & txtName.Text & "<br>")
     Response.Write("lblGreeting = " & lblGreeting.Text _
          & "<br>")
End Sub

Sub Page_Load(sender As Object, E As EventArgs)
     Response.Write("Page_Load<br>")
     Response.Write("IsPostBack = " & IsPostBack & "<br>")
     Response.Write("txtName = " & txtName.Text & "<br>")
     Response.Write("lblGreeting = " & lblGreeting.Text _
          & "<br>")
End Sub

Sub Page_PreRender(sender As Object, E As EventArgs)
     Response.Write("Page_PreRender<br>")
     Response.Write("txtName = " & txtName.Text & "<br>")
     Response.Write("lblGreeting = " & lblGreeting.Text _
          & "<br>")
End Sub

</SCRIPT>
</HEAD>
<BODY>
<FORM RUNAT="SERVER">Your name:&nbsp;
<asp:textbox id=txtName Runat="server"></asp:textbox>
<p><asp:button id=cmdEcho onclick=cmdEcho_Click Text="Echo"
runat="server" tooltip="Click to echo your name">
</asp:button></p>
<asp:label id=lblGreeting runat="server"></asp:label>
<P></P>
</FORM>
</BODY>
</HTML>

When we display the page the first time the output reflects the fact that both the text box and the label are empty, since we have entered no information. IsPostBack is false. Now enter a name and click the Echo button. We obtain the following output from our handlers for the page events:

Page_Init
txtName =
lblGreeting =
Page_Load
IsPostBack = True
txtName = Robert
lblGreeting =
Page_PreRender
txtName = Robert
lblGreeting = Hello, Robert

In Page_Init there is no information for either control, since view state is not available at page initialization. In Page_Load the text box has data, but the label does not, since the click-event handler has not yet been invoked. IsPostBack is now true. In Page_PreRender both controls now have data.

Click Echo a second time. Again, the controls have no data in Page_Init. This time, however, in Page_Load the view state provides data for both controls. Figure 14–9 shows the browser output after Echo has been clicked a second time.

Figure 14-9Figure 14-9 Browser output after Echo has been clicked a second time.

Page Directive

An .aspx file may contain a page directive defining various attributes that can control how ASP.NET processes the page. A page directive contains one or more attribute/value pairs of the form

attribute="value" 

within the page directive syntax

<@  Page ... @>

Our example program HelloCodebehind.aspx illustrates an .aspxpage that does not have any code within it. The code-behind file HelloCode-behind.aspx.vb that has the code is specified using the Src attribute.

<!-- HelloCodebehind.aspx --> 
<%@ Page Language="VB" Src="HelloCodebehind.aspx.vb"
Inherits=MyWebPage %> 
... 

Src

The Src attribute identifies the code-behind file.

Language

The Language attribute specifies the language used for the page. The code in this language may be in either a code-behind file or a SCRIPT block within the same file. Values can be any .NET-supported language, including C# and VB.NET.

Inherits

The Inherits directive specifies the page class from which the .aspx page class will inherit.

Debug

The Debug attribute indicates whether the page should be compiled with debug information. If true, debug information is enabled, and the browser can provide detailed information about compile errors. The default is false.

ErrorPage

The ErrorPage attribute specifies a target URL to which the browser will be redirected in the event that an unhandled exception occurs on the page.

Trace

The Trace attribute indicates whether tracing is enabled. A value of true turns tracing on. The default is false.

Tracing

ASP.NET provides extensive tracing capabilities. Merely setting the Trace attribute for a page to true will cause trace output generated by ASP.NET to be sent to the browser. In addition, you can output your own trace information using the Write method of the TraceContext object, which is obtained from the Trace property of the Page. The page HelloTrace.aspx illustrates using tracing in place of writing to the Response object.

<!-- HelloTrace.aspx -->
<%@ Page Language="C#" Debug="true" Trace = "true" %>
<HTML>
<HEAD>
   <SCRIPT RUNAT="SERVER">
Sub cmdEcho_Click(Source As Object, e As EventArgs)
    lblGreeting.Text="Hello, " & txtName.Text
End Sub

Sub Page_Init(sender As Object, E As EventArgs)
      Trace.Write("Page_Init<br>")
      Trace.Write("txtName = " & txtName.Text & "<br>")
      Trace.Write("lblGreeting = " & lblGreeting.Text _
& "<br>")
End Sub
...

Figure 14–10 shows the browser output after the initial request for the page. Notice that the trace output is shown after the form, along with trace information that is generated by ASP.NET itself.

Figure 14-10Figure 14-10 Browser output showing trace information.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020