Understanding the ASP.NET Page Life Cycle

The process by which an ASP.NET page is rendered to the browser consists of multiple stages. These stages all have a very distinct purpose in the creation and rendering of your page. A common problem among new ASP.NET developers is injecting code into the wrong stage in the page's life cycle. If you put code in the wrong place, controls that you expect to exist might not exist, or the controls might exist but their state might be nonexistent or unpredictable. This section gives you an introduction to the process that ASP.NET uses to render pages. Understanding this process is absolutely crucial to continuing with more advanced aspects of ASP.NET, such as creating and using your own custom controls.

Stages of ASP.NET Page Rendering

To support the object-oriented framework, the event-driven model, and the capability to persist control state between page requests, ASP.NET has several distinct stages in the life cycle of a page. One key concept to remember is that no matter what, a page will be instantiated and destroyed during the same request. The sequence of stages and events in the life cycle is what allows a page to create a control hierarchy, reconstitute itself from persisted ViewState, render its output, and clean up temporary resources used by the page.

Table 22.1 provides you with the list of stages that occur in the lifetime of an ASP.NET page. It is extremely important to understand these stages before you start creating your own ASP.NET applications.

Table 22.1. ASP.NET Page Life Cycle Stages



Request for Page

The page request starts before a page has been instantiated. When a user requests a page from the web server, ASP.NET checks to see if there is a cached version of the rendered output that can be displayed. If so, the cached version is returned without rerunning the entire Page life cycle. If there is no cached version available, the process continues to the Page Start stage.

Page Start

During this stage, the Page is instantiated and the input/output properties Request and Response are set. In addition, the IsPostback property is set, indicating whether the request is a new request, or a request originating from a previously rendered ASP.NET page. The UICulture property is also set during this stage.


During this stage, controls are instantiated and the page's control hierarchy is constructed. Theme and skin information is applied to the page during this stage. Note that the controls are essentially empty at this stage and none of their properties have been restored from view state if the page is a postback.


During this stage, control properties are restored from state if the request is a postback.


The validation stage is used to validate the state of all controls on the page. The Validate() method of all validator controls on the page is invoked, which then determines the state of the page's IsValid property. Validation is used to enforce rules on user input.

Postback Event Handling

If the request is a postback, then postback events in response to such things as button clicks, selected index changes, and more are invoked. When creating event handlers, it is important to remember that your event handlers are called after the page's Load stage.


The Render stage is where each control in the Page's control hierarchy is asked to contribute its own rendered output to the rendered output of the entire page. The Page's view state is also included in the output of the page as a hidden form variable at this point.


When the final rendered output has been produced, and there is no more work to be done by any of the child controls to produce output, the Unload stage is entered. In this stage, child controls and the page itself can dispose of resources that were used during any previous stage of the Page life cycle.

ASP.NET Page Life Cycle Events

Most of the stages described in Table 22.1 correspond to events that can be handled by your own code. Handling these events allows you to control when your code is executed by placing the code in specific stages of the page's life cycle. Controls that were supplied with ASP.NET, written by you, or provided by a third party are engaged in the life-cycle stages by having their own miniature versions of the Page life cycle. The Page involves the control in the appropriate stage of the life cycle by triggering control events.

Table 22.2 contains a list of Page events, their descriptions, and typical uses.

Table 22.2. Page Life Cycle Events




Called at the beginning of the Initialize stage. Used to create dynamic controls, set master pages and themes dynamically, and to read/write user profile data. Note that control properties have not yet been restored from view state when this event is called.


Called during the Initialize stage to initialize control properties.


Called during the Load stage to read control properties or update existing control properties. At this stage, control properties have been reconstituted from view state.

(Control Events)

Controls have their events invoked at this stage, such as responding to a button click, the selected index changing on a ListBox, and so on. If your page has validation controls, check the IsValid status of the controls and the page before continuing with your event handler.


This event is triggered just before the final version of the page is rendered. If you need to make final tweaks to properties of controls based on information that is only available immediately before rendering, this is the event you should use.


This event is called immediately before the page is discarded by ASP.NET to dispose of costly resources such as database connections. Also commonly used to write final logging and tracing information.

To further illustrate the page life-cycle events, the code in Listing 22.1 shows you how to create a page that prints some text to the rendered output during each of the crucial life-cycle events. There is a button on the page so that you can click it and see where its event handler appears in the life cycle, as well as see the use of the IsPostback property.

To create this code, open up Visual Studio 2005 and choose File, New, Web Site. Make sure it's a standard C# website and not a starter kit or web service. Drag a single button from the Toolbox onto the form. Double-click it to create an event handler. Switch to the code view and override the many OnXxxx() methods that are already configured as event handlers for the events described in Table 22.2. Your default.aspx.cs file should look very similar to the one in Listing 22.1.

Listing 22.1. Default.aspx.cs

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page {     protected void Page_Load(object sender, EventArgs e)     {         if (Page.IsPostBack)             Response.Write("This is a postback request.");         else         {             Response.Write("This is a new request.");         }         Response.Write("<br/>Page_Load called.<br/>");     }     protected override void OnPreInit(EventArgs e)     {         Response.Write("Pre-Init called.<br/>");         base.OnPreInit(e);     }     protected override void OnInit(EventArgs e)     {         Response.Write("Init called.<br/>");         base.OnInit(e);     }     protected override void OnInitComplete(EventArgs e)     {         Response.Write("Init completed.<br/>");         base.OnInitComplete(e);     }     protected override void OnLoad(EventArgs e)     {         Response.Write("Load called.<br/>");         base.OnLoad(e);     }     protected override void OnLoadComplete(EventArgs e)     {         Response.Write("Load completed.<br/>");         base.OnLoadComplete(e);     }     protected override void OnUnload(EventArgs e)     {         // cannot display output here because Response/Request         // are not available during this stage.         base.OnUnload(e);     }     protected void btnSubmit_Click(object sender, EventArgs e)     {         Response.Write("You clicked the submit button.<br/>");     } } 

When you run this application for the first time, you see the output shown in Figure 22.1.

Figure 22.1. Page life-cycle event demonstration.

After you click the test button, the output now includes information from the event handler created for the submit button, as shown in Figure 22.2.

Figure 22.2. Page life-cycle event demonstration, after clicking the button.

As you learn more about control building and you work more with ASP.NET pages, the purpose of the events discussed in this section will become clearer to you.

A fairly new concept, the postback, was introduced in Listing 22.1. ASP.NET outputs a JavaScript library that contains many helper functions. One of those functions causes the page to "'post back"' on itself. This function places information in the page's view state that indicates which button was clicked (or which control caused the postback). When the Page life cycle gets to the control event stage, it compares the event that triggered the postback with the event handlers contained in the page, and invokes the appropriate event. In the case of the code in Listing 22.1, the btnSubmit_Click handler was called. The combination of the Page life cycle, postbacks, and some relatively hidden plumbing allows ASP.NET to present the developer with an event-driven model that closely resembles the event-driven model with which Windows developers are very familiar.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

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