home » articles » ASP.NET Page Lifecycle

ASP.NET Page Lifecycle

change text size: A A A

3/11/2009 by vivek_iit


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.

Basics: 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 (WebForm.aspx.cs) which contains the code for the events and other methods related to a Page, and the designer ASPX file, 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".

Real Thing: 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:

http://msdn2.microsoft.com/en-us/library/1whwt1k7%28VS.80%29.aspx

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

Important Note: All events except the Init() and Unload() are fired from outermost to the innermost control. For e.g., a user control’s init event would fire before the Page_Init() event of its parent Page class.

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 = “Hello”, 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 and add your custom code:

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:



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();

3. LoadViewState

 This will only fire if the Page has posted back (IsPostBack == true). Here the runtime de-serializes the view state data from the hidden form element and loads all controls who have view state enabled.

4. LoadPostBackData

Again, this method will only fire if the Page has posted back.
In this event the controls which implement IPostBackDataHandler interface gets loaded by the values from the HTTP POST data. Note that a textbox control does not gets its value from the view state but from the post data in the form in this event. So even if you disable view state for a particular control, it can get its value from the HTTP POST data if it implements IPostBackDataHandler interface.

Also, an important point to note is that if we have a DropDownList control and we have dynamically added some items to it, the runtime cannot load those values unless the view state is enabled (even if the control derives from IPostBackDataHandler). The reason being that HTTP Post data has only one value per control, and the entire value collection is not maintained in the PostData but in view state.

5. Page_Load

This is the most popular method and the first one for all beginner developers to put their code. Beginners may also think that this is the first method which fires for a Page class. This can lead to a lot of confusion which makes understanding the Page lifecycle all the more important.

Note: If the page has any user control, then it's Load method will fire after the Page class's Load method. The reason as explained earlier is the fact that all method except the Init() are fired from the outermost control to the innermost. So after Page_Load(), load methods of all other controls are fired recursively.

6. 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.

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.

8. SaveViewState
Here, the ViewState of the controls gets saved in the form's hidden control.

9. Render

In this method all controls are rendered recursively (i.e. Render method of each control is called).

10. Unload

Here you can have the page and controls perform clean-up operations. This event has no relevance besides clean up operations because the Page has already rendered.

Dynamic Controls

Now we have seen the important events in the Page lifecycle, let's focus on how to create and maintain state of dynamically generated controls. Many times we need to generate controls dynamically for specific business use cases. For example, I was managing a famous hotel reservation website project and one of my team members was facing an issue in handling the Reservation screen. There was a TextBox where the user enters the number of
rooms, and based on that value, dynamic usercontrols having a room's detailed info were created at runtime.

The developer complained that although he was able to generate user controls as runtime in a for loop, but was unable to save their state. When I looked into the code, I noticed that the code to generate controls was written in a Button's Click event handler. Now as we dicussed above, event handlers like Button_Click() fire much later than LoadViewState() and LoadPostData(), where the control values get loaded from the view state and form's Post data.

So unless he recreates the controls in the Page_Init() or Pre_Init() methods (which occur before LoadViewState and LoadPostData), the control values modified by the user won't get reloaded next time.

Now, when he put the code in the Page_Init() event, he was unable to get the number of rooms entered by the user in the TextBox (which was a static control). The reason being that in Page_Init(), control values are initilized to their design time default values, and do not reflect the user entered values unless they are loaded from the POST data or the view state, a process which occurs later.

So the only way to access the user entered value in the control is to get the value from the form's POST data. Here is the code:


protected override void OnInit(EventArgs e)

{
//get value of the TextBox from HTTP POST data

string selectedValue ;
if(Request.Form["txtNoOfRooms"] != null)

selectedValue = Request.Form["txtNoOfRooms"].ToString();


//code to create controls dynamically...

...............


base.OnInit(e);
}


Note: Thanks to Mike Banavige of ASP.NET forums, I added this section. If you create a dynamic control in the Page_Load event, and add it to a PlaceHolder or Panel (with view state turned on), then this dynamic control will maintain its state even though it was not created in the Page_Init(). Why?

The reason is the fact that once a control is added to the control tree of the page, TrackViewState() method is responsible for tracking the state. This method gets fired automatically whenever the control is added to the control tree. Due to this reason, any modifications to the control (like adding items etc) should be done *only after* the dynamic control has been added to the control tree of the Page class, else the state would be lost. See the code below:

protected void Page_Load(object sender, EventArgs e)
{
//create a dynamic dropdown


DropDownList d = new DropDownList();

PlaceHolder1.Controls.Add(d); // TrackViewState() gets fired for our dropdown, so state is maintained


if (!IsPostBack)

{

d.Items.Add("test1");
d.Items.Add("test2");

}

}

This will not work:

protected void Page_Load(object sender, EventArgs e) 

{

//create a dynamic dropdown

DropDownList d = new DropDownList();

if (!IsPostBack)

{

d.Items.Add("test1");

d.Items.Add("test2");

}

PlaceHolder1.Controls.Add(d); //"test1" and "test2" values are lost

}

Summary

I have tried to explain relevant events in the Page lifecycle and their importance with some gotchas. I will keep updating this article with more tips and tricks, besides readers are welcome to point out mistakes and suggest corrections and give feedback!

An important thing to remember here is that the entire lifecycle is repeated on every request. The Page class gets re-instantiated and after serving the request gets unloaded. Once we are clear with the sequence of the events, we can structure our code well to suit different use case requirements. 

To rate this article please register or login

Author

vivek_iit vivek_iit (Member since:11/27/2008)
I am one of the administrators at CodeAsp.Net and I love programming, architecting solutions, code reviews, teaching and writing about ASP.NET.

Comments (11)

  • sanjeev 2/9/2009 1:04:20 PM by:  sanjeev
    Nice. cheers, **SSN**
  • 2/27/2009 1:48:33 PM by: 
    This is really good! Keep them coming!
  • 3/27/2009 1:15:12 PM by: 
    Really nice, helped a lot in clearing doubt related to page life cycle
  • 4/3/2009 3:14:42 AM by: 
    Thanks for suc a nice and helpful article on Page Life Cycle. Keep up sharing your knowledge on ASP.NET :)
  • 4/21/2009 11:20:19 PM by: 
    good one
  • 8/20/2009 8:52:54 AM by: 
    Thanks. This article is really good.
  • 8/29/2009 6:07:40 AM by: 
    Simple precise and clear. Good one.
  • 9/3/2009 8:25:31 AM by: 
    excellent article for page lifecycle. This cleared a lot of doubt regarding page events and control events of mine...anyways thanks a lot for this sharing.
  • 9/8/2009 7:23:06 AM by: 
    its really good
  • 9/13/2009 12:50:15 PM by: 
    Excellent explanation. Hope you mention about the sequence of events if page has user controls. Thanx for the article.
  • 10/30/2009 6:45:01 AM by: 
    Nice article. Keep ahead with new trouble shooting. - Raja

Post a comment

Comment (No HTML)  

Type the characters:
 *
 
   

Related articles

  • ASP.NET MVC Framework Tutorial
    The Model View Controller (MVC) is a buzzword in the ASP.NET community, thanks to the upcoming ASP.NET MVC Framework that Microsoft has launched recently. The Framework allows easier adoption of the different MVC patterns in our web applications. In this ...
  • The Importance of Web Design and Website Credibility
    One of the most significant functions of websites today is to provide credibility for your business. The credibility of your website is becoming more and more an increasingly important area to understand. And it's an area that many web developers and web ...
  • Dependency Injection And Factory Design
    Using simple design patterns can help create flexible software which is also easy to maintain and also reduce costs. By the help of this article I wanted to explain how this flexibility can be achieved in real world programs. Also if there are any suggest...
  • How to Restore a MSSQL 2005 Database
    Restoring a MSSQL 2005 database can mean problems for those that do not know how to do it properly. Especially if you are restoring this database on a different server than what it was created on. Read how to do it here.
  • ASP.NET TreeView CheckBoxes Check All – JavaScript
    ASP.NET TreeView CheckBoxes – Check All – JavaScript

Join CodeAsp.Net for FREE Today!

It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.

enter your email address:

Latest Articles RSS Feed

Latest Articles

  • Hi Friends, Many times we came cross the requirement when we need to access the dropdownlist's selectedindexchanged event inside the gridview, like in a shopping cart changing the item's quantity or binding the other dropdown based on the first dropdown.
  • This is the approach that I have adopted to develop Expandable / Collapsible Panel Control through JavaScript. Please report bugs, errors and suggestions to improve this control.
  • This is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know about bugs and/or errors & give suggestions to improve this ListBox control.
  • I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine.
  • So, this is my approach to implement an ASP.NET slide show using the DataList. I have tried my best to keep it bug free. I will most welcome suggestions and criticism for further improvements of this user control. I have tested this user control on various browsers and it works fine.
  • As we all knows that Repeater and DataList does not have auto paging support technique like Gridview or Datagrid, but we can achieve this through PagedDataSource. By using PagedDataSource we can implement paging in Repeater or DataList. Now in our mind there is question arise what is PagedDataSource. PagedDataSource is a class which encapsulates
  • So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.
  • So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.
  • So this is the approach that I've adopted to solve the Hover Delay problem. Although originally I developed Hover Delay to deactivate the click event for 1 second on a GridView row, later I also used Hover Delay to deactivate Drag n Drop of GridView rows. Kindly let me know if any one has some other better or different solution.
  • In this article I will explain how to import data from EXCEL to SQL in ASP.NET . In many situations we have data in the form of excel sheet but we have the requirement to have that data in SQL SERVER DB. I have explained importing data both from Excel 97-2003 as well as Excel 2007 format.
  • The source code shows how to use Regular Expressions in C#. The code Functions written for Validation Alphabet, AlphaNumeric, Integer, Postive Integer, Floating point numbers. You just cut copy these functions and use in any program.
  • That’s all about this technique. Just download the sample application and happy CSS! I have tested this application on various browsers and it worked fine.
  • This script is cross-browser compatible and fast as it iterates elements of a specific tag inside a target element [GridView] rather than iterating in a whole form. It searches the elements of a specific type in a particular column of the target element [GridView].
  • This Article is used to insert a numeric value on the sever control(text box) This is a java script code for the the client side validation. On Page Load Event You can change the events in txtNoOfQuestion.Attributes.Add("onkeypress", "return numericOnly(this);"); like onfocus events like other according to needs.
  • I have toggled visibility of all TD elements of a GridView column in order to create an illusion of smooth dynamic effect with the help of setTimeout method through recursion. Different browsers have different effects of Expanding / Collapsing GridView Columns. In Internet Explorer 7/8, Safari, Google Chrome and Opera, it seems that columns are Exp
  • In this article, I've used the setTimeout method in order to achieve a smooth expand/collapse functionality.
  • Introduction I am going to present here a functionality that selects / deselects all checkboxes of a particular column inside a GridView control, provided the header checkbox of that column is checked or unchecked using JavaScript. This functionality also has a feature that when all checkboxes of a particular column inside the GridView are check
  • This article describes how to toggle the states of all CheckBoxes inside a particular DataGridView column.
  • This article describes how to apply client-side mouse over & mouse out effects on the GridView’s rows.