Book Chapter

Chapter 1: 'Architecture'


Download chapter 1: 'Architecture'


Excerpted from the book "Essential ASP.NET 2.0," ISBN 0321237706, Copyright 2006. Written permission from Addison-Wesley is required for all other uses. Copyright © 2006 Addison-Wesley . All rights reserved.







Chapter Excerpt:


Page Lifecycle

One of the most important things to understand when building Web applications with ASP.NET is the sequence of events during the processing of a page. If you're not careful, you can make changes to a control that are then overwritten, which can result in unexpected behavior. As you build a page, you must take care that the code you write is called at the right time during the request processing to have the impact you expect. Fortunately, there are many events at your disposal in the Page base class. You can usually find the correct point in time to populate controls with default values, dynamically alter the control hierarchy, harvest POST data from the client, or whatever else you are trying to accomplish.

Common Events

The most common events to handle in ASP.NET are the Init and Load events. The Load event is issued prior to the rendering of a page, and it is the ideal location to initialize control state. It is also called after the state in a POST request has been processed and used to populate the control hierarchy, and so it can be used to inspect the contents of data sent by the client. The Init event, on the other hand, is called before any state restoration occurs and is commonly used to prepare the Page for processing a request. You can even do things like modify the control hierarchy in the Init event if there are dynamic changes you would like to make to a page. Most ASP.NET applications use a fairly standard event scheme in their interactive pages.
  1. They initialize the state of controls for the first time in the Load event if it is the initial GET request to a page (the IsPostBack property of the page is set to false).
  2. Next, they process user responses inside the server-side event of the control that generates the subsequent POST request.
Listings 1-13 and 1-14 show an example of this common practice with a page and its codebehind class.

Listing 1-13: CommonEvents.aspx



<%@ Page Language="C#" AutoEventWireup="true"
                CodeFile="CommonEvents.aspx.cs"
                Inherits="EssentialAspDotNet.CommonEvents" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Common Events Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h3>Enter name: </h3>
    <asp:TextBox id="_nameTextBox" runat="server"/>
    <h3>Personality: </h3>
    <asp:DropDownList id="_personalityDropDownList" runat="server" />
    <asp:Button id="_enterButton" Text="Enter" runat="server"
                OnClick="_enterButton_Click" /><br />
    <asp:Label runat="server" id="_messageLabel" />
    </div>
    </form>
</body>
</html>


Listing 1-14: CommonEvents.aspx.cs

namespace EssentialAspDotNet
{
  public partial class CommonEvents : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        _personalityDropDownList.Items.Add(new ListItem("extraverted"));
        _personalityDropDownList.Items.Add(new ListItem("introverted"));
        _personalityDropDownList.Items.Add(new ListItem("in-between"));
      }
    }
    protected void _enterButton_Click(object sender, EventArgs e)
    {
      _messageLabel.Text = "Hi " + _nameTextBox.Text +
                           ", you selected " +
                           _personalityDropDownList.SelectedItem.Text;
    }
  }
}

New Events

This release of ASP.NET introduces even more events in the Page class, increasing the number of options you have for how to interact with the request processing of the Page. For the most part, the new events are "pre" and "complete" events that wrap one of the existing events. For example, there is now both a PreLoad event as well as a LoadComplete event in addition to the standard Load event. Figure 1-2 shows the updated sequence of events as well as the activities that occur during the processing of the page between the events.

Most notable among these new events are the PreInit and LoadComplete events. PreInit is important because, as you will see in Chapter 2, themes and master pages are applied between PreInit and Init. This means that PreInit is your only opportunity to make programmatic modifications to the selected theme or associated master page of a page. The LoadComplete



event is also potentially quite useful as it is fired after the server-side events have fired but before the PreRender event takes place. Many applications written in ASP.NET today resort to using the PreRender event to make last-minute changes to control contents after server-side events fire. LoadComplete is now the proper place to make post-event modifications to a control, leaving PreRender as a hook for other activities.

Note that the PreInit, InitComplete, PreLoad, LoadComplete, PreRender- Complete, and SaveStateComplete are brand new events, and that they are only available in the Page class but not in individual controls as the other events are.

Implicit Event Subscription

One of the first things you will notice that is different in ASP.NET 2.0 is that Visual Studio 2005 creates event handlers for page events by enabling AutoEventWireUp and using specially named methods that are implicitly registered as event handlers—instead of explicitly registering delegates as the previous release did.3 For example, to add a handler for the Load event of the Page class, Visual Studio 2005 adds a method to your codebehind class (or inline in a server-side script block) named Page_Load. Table 1-1 shows the complete list of method names that will be implicitly subscribed to events if they are added to your Page class.

Implicit delegate wireup occurs when a page has the Auto- EventWireUp attribute set to true (which is the default), and one or more of the page's methods matches one of the names shown in Table 1-1. The method must also have the correct signature expected by the delegate defining the event (typically just EventHandler). At the beginning of the request cycle, the Page class invokes its SetIntrinsics method, which in addition to setting the intrinsics (meaning the Response, Request, Session, Application, and so on) calls the TemplateControl base class' HookUp- AutomaticHandlers method. This method walks through the list of method names shown in Table 1-1 and uses reflection to identify methods with the same name and proper signature defined in your class. If it finds a match, it creates a new delegate of the appropriate type, initializes it with your method, and adds it to the list of delegates to fire when that event occurs.


Each of these events is fired by a virtual method defined in the Page base class (or a virtual method in the Control base class and inherited by Page). This means that it is technically possible to register for any of these events in three different ways. For example, to handle the Load event, you can do any of the following:

  • Wire up a delegate explicitly to the event yourself (typically in your Page's Init handler).
  • Write a method named Page_Load with the event signature.
  • Override the virtual OnLoad method.
Each of these techniques essentially accomplishes the same task, and in the end it doesn't matter which way you do it. The virtual method override is going to be marginally faster than the explicitly or implicitly wired delegate approaches, but in general the difference in overhead will typically be dwarfed by other activities in your page (like data access). If you are using Visual Studio 2005, the technique it uses for you by default is the implicit delegate wireup based on the method's name.

Chapter 1: 'Architecture'

Visit the Addison-Wesley website for a detailed description and to learn how to purchase this title.

This was first published in November 2006

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: