ASP.NET Page Lifecycle

Introduction

Understanding Page lifecycle is very crucial in order to develop ASP.NET applications. Most beginners tend to get confused while dealing with “dynamic controls” and face problems like losing values, state etc on postbacks. Since HTTP is stateless, the nature of web programming is inherently different from windows application development, and the Page lifecycle is one of the primary building blocks while learning ASP.NET. The sequence of events, especially while working with MasterPages in ASP.NET 2.0, has become slightly more complex and this article is aims to shed some light on these events by explaining the order and importance of each event.

Background

Whenever the user requests a particular “.aspx” page in an application, a lot of interesting things happen on the web server where the application is hosted. Understanding this sequence of events will help us to program and respond to events properly and also clear any confusion which generally arises due to the stateless nature of web programming.

The New Compilation Model and the Partial Classes

Each web form in an ASP.NET application derives directly or indirectly from a “System.Web.UI.Page” class. A web form has two components: a code behind file (Default.aspx.cs) which contains the code for the events and other methods related to a Page, and the designer ASPX file(Default.aspx), which contains HTML control declarations and events (in the Visual Studio 2005 Web Application project model, we have a designer class named WebForm.aspx.designer.cs).

In ASP.NET 2.0, we do not need to define the control variables as well as there event handlers in the code behind, thanks to Partial classes. In ASP.NET 1.x, all this code was auto generated and placed in the code behind file under InitializeComponent() section. But in version 2.0, the runtime will create a partial class dynamically from the ASPX page containing all this info and merge it with the code behind partial class. This will help in making the actual code behind class a lot cleaner and more manageable.

Also, this would eliminate the name change related issues which were common in VS 2003 (if we change any control’s ID, it had to be changed everywhere and VS used to modify the code many times). All control related events are defined in the ASPX markup code. So having a single place for controls names and event handlers is cleaner and flexible, whereas the previous VS 2003 model was more “brittle”.

The Page life cycle

It is very important to know that for each request, the Page class is instantiated everytime from “scratch”. Which means that any values or whatever state it had previously will get lost unless we use one of the various state maintainance mechanisms provided by ASP.NET like Application, Session, Cache variables or Cookies.

Side Note: View state in ASP.NET 2.0 has changed and now comprises of two parts: Control State and View state. Refer this article for details.

Below is the sequence of events which fire up sequentially with explanation on the relative importance with respect to web programming in code behind:

1. PreInit()

In this Page level event, all controls created during design time are initialized with their default values. For e.g., if you have a TextBox control with Text property = “ShivaSoft”, it would be set by now. We can create dynamic controls here.

This event occurs only for the Page class and “UserControls / MasterPages do not have this method to override“.

Sample code where you can override this method :

Syntax :

    protected override void OnPreInit(EventArgs e)
    {
        //custom code
        base.OnPreInit(e);
    }

Note that PreInit() is the only event where we can set themes programmatically.

Special Case with MasterPages

It is important to note that Master Page is treated like a control in the Content Pages.

So if a Page has a Master Page associated with it, then the controls on the page will not be initialized and would be null in this stage. Only after the Init() event starts, you can access these controls directly from the page class. Why?

The reason being that all controls placed in the Content Page are within a ContentPlaceholder which is a child control of a MasterPage. Now Master Page is merged and treated like a control in the Content Pages. As I mentioned earlier, all events except the Init() and Unload() are fired from outermost to the innermost control. So PreInit() in the Page is the first event to fire but User Controls or MasterPage (which is itself a Usercontrol) do not have any PreInit event . Therefore in the Page_PreInit() method, neither the MasterPage nor any user control has been initialized and only the controls inside the Page class are set to their default values. Only after the Page_PreInit() event the Init() events of other controls fire up.

See the diagram below showing control hierarchy after the Page_Init() event:

Control hierarchy after page_init() event in asp.net page life cycle
Control hierarchy after page_init() event in asp.net page life cycle

2. OnInit()

In this event, we can read the controls properties (set at design time). We cannot read control values changed by the user because that changed value will get loaded after LoadPostData() event fires. But we can access control values from the forms POST data as:

string selectedValue = Request.Form[controlID].ToString();

Syntax:

    protected override void OnInit(EventArgs e)
    {
        //custom code
        base.OnInit(e);
    }

3. PreLoad

Use this event if you need to perform processing on your page or control before the Load event.
After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
The PreLoad event is raised after all postback data processing and before the Load event.

    protected override void OnPreLoad(EventArgs e)
    {
        //custom code
        base.OnPreLoad(e);
    }

4. Load
This method notifies the server control that it should perform actions common to each HTTP request for the page it is associated with, such as setting up a database query. At this stage in the page lifecycle, server controls in the hierarchy are created and initialized, view state is restored, and form controls reflect client-side data.

Use the IsPostBack property to determine whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.
Control Event Handlers

syntax:

    protected void Page_Load(object sender, EventArgs e)
    {
        //code here
    }

5. Control Event Handlers
These are basically event handlers (like Button1_Click()) which are defined for controls in the ASPX markup. Another source of confusion arises when the developer thinks that an event handler like Button_Click() should fire independently (like in windows apps) as soon as he clicks a Button on the web form, forgetting that Page_Load will fire first before any event handlers.

syntax:

    void GreetingBtn_Click(Object sender, EventArgs e)
    {
        //code
    }

6.OnLoadComplete
The LoadComplete event occurs after all postback data and view-state data is loaded into the page and all controls on the page. In order for view state to work for controls that are added dynamically, they must be added in or before the pre-render stage of the page life cycle.
syntax:

    protected override void OnLoadComplete(EventArgs e)
    {
        //custom code
        base.OnLoadComplete(e);
    }

7. PreRender
This event is again recursively fired for each child controls in the Page. If we want to make any changes to control values, this is the last event we have to peform the same.

    protected override void OnPreRender(EventArgs e)
    {
        //custom code
        base.OnPreRender(e);
    }

8.SaveStateComplete
Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

    protected override void OnSaveStateComplete(EventArgs e)
    {
        //custome code
        base.OnSaveStateComplete(e);
    }

9.Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup that is sent to the browser.
Syntax:

    protected override void Render(HtmlTextWriter writer)
    {
        //custom code
        base.Render(writer);
    }

10.Unload
This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

    protected override void OnUnload(EventArgs e)
    {
        //custom code
        base.OnUnload(e);
    }

To read more on Page life cycle, please refer this MSDN article

ASPX PageLife Demo Source code – Output on Debug Console

Posted

in

,

by

Tags:


Related Posts

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading