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  runat="server">     <div>     <h3>Enter name: </h3>     <asp:TextBox  runat="server"/>     <h3>Personality: </h3>     <asp:DropDownList  runat="server" />     <asp:Button  Text="Enter" runat="server"                 OnClick="_enterButton_Click" /><br />     <asp:Label runat="server"  />     </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.

Figure 1-2. Events in the page lifecycle


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, PreRenderComplete, 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 handlersinstead 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.

[3] This is only true for Web applications written in C#, as VB.NET still uses its "Handles" syntax to wire up control events.

Table 1-1. Method names and the events they bind to in ASP.NET 2.0

Method Name

Event

Page_PreInit

Page.PreInit

Page_Init

Control.Init

Page_InitComplete

Page.InitComplete

Page_PreLoad

Page.PreLoad

Page_Load

Control.Load

Page_LoadComplete

Page.LoadComplete

Page_PreRender

Control.PreRender

Page_DataBind

Control.DataBinding

Page_PreRenderComplete

Page.PreRenderComplete

Page_SaveStateComplete

Page.SaveStateComplete

Page_Unload

Control.Unload

Page_Error

TemplateControl.Error

Page_AbortTransaction

TemplateControl.AbortTransaction

OnTransactionAbort

TemplateControl.AbortTransaction

Page_CommitTransaction

TemplateControl.CommitTransaction

OnTransactionCommit

TemplateControl.CommitTransaction


Implicit delegate wireup occurs when a page has the AutoEventWireUp 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' HookUpAutomaticHandlers 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.




Essential ASP. NET 2.0
Essential ASP.NET 2.0
ISBN: 0321237706
EAN: 2147483647
Year: 2006
Pages: 104

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net