Skip to main content

ASP.NET Page Life Cycle with example


In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page.

Methods
Description
Page_PreInit
Before page Initialization
Page_Init
Page Initialization
LoadViewState
View State Loading
LoadPostData
Postback Data Processing
Page_Load
Page Loading
RaisePostDataChangedEvent
PostBack Change Notification
RaisePostBackEvent
PostBack Event Handling
Page_PreRender
Page Pre Rendering Phase
SaveViewState
View State Saving
Page_Render
Page Rendering
Page_Unload
Page Unloading

PreInit : The entry point of the page life cycle is the pre-initialization phase called “PreInit”. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event. 

Init : This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself. 

InitComplete: Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback

PreLoad : Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance
(1)Loads ViewState : ViewState data are loaded to controls
(2)Loads Postback data : postback data are now handed to the page
Load: The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

Control (PostBack) event(s) :ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event.

LoadComplete :This event signals the end of Load.
 
PreRender : Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved. For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.

SaveStateComplete :Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored. 

Render : This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

UnLoad : This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on-
(a)Instances of classes i.e. objects
(b)Closing opened files
(c)Closing database connections
Below is example of the ASP.Net Life Cycle
HTML Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Page Button" />
</div>
</form>
</body>
</html>
Code Default.aspx
using System;
public partial class _Default : System.Web.UI.Page
{
int i = 0;
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write( "" + (++i).ToString() + " Page Pre-Init");

}
protected override void OnInit(EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Init");

}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Init Completed");

}
protected void Page_Load(object sender, EventArgs e)
{
ViewState["test"] = "Test";
Response.Write("" + (++i).ToString() + " Page Load");

}
protected override void OnPreRender(EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Pre Render");

}
//protected override void Render(HtmlTextWriter writer)
//{
// //Response.Write("" + (++i).ToString() + " Render");

//}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Button Click");

}
protected override void OnUnload(EventArgs e)
{
// Response.Write("" + (++i).ToString() + " Unload");

}
public override void Dispose()
{
// Response.Write("" + (++i).ToString() + " Dispose");

}
protected override object SaveViewState()
{
Response.Write("" + (++i).ToString() + " Page Save View State");
return base.SaveViewState();
}
public void RaisePostBackEvent(string eventArgument)
{
Response.Write("" + (++i).ToString() + " Page Raise Post Back Event");

}
public void RaisePostDataChangedEvent()
{
Response.Write("" + (++i).ToString() + " Page Raise Post Data Change Event");

}
protected override void LoadViewState(object o)
{
Response.Write("" + (++i).ToString() + " Page Load View State");
base.LoadViewState(o);

}
private void Page_LoadComplete(object sender, System.EventArgs e)
{
Response.Write("" + (++i).ToString() + " Page Load Completed");
}
}
OUTPUT
When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal as below only Page_Unload and Dispose are not shown here.
Suppose the Button event get fire then it will create event as below (again Page_Unload and Dispose are not shown here because page already load when these event occurs)

Comments

  1. Very Helpful article. I was looking for such detail, but simple atricle. Thanks.

    ReplyDelete
  2. good one
    http://dotnetcontents.blogspot.in/2012/08/aspnet-page-life-cycle-events.html

    ReplyDelete
  3. reallly it helped alot thanks

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

Connected and disconnected architecture in ADO.Net with Example

Connected Architecture of ADO.NET The architecture of ADO.net, in which connection must be opened to access the data retrieved from database is called as connected architecture. Connected architecture was built on the classes connection, command, datareader and transaction.  Connected architecture is when you constantly make trips to the database for any CRUD (Create, Read, Update and Delete) operation you wish to do. This creates more traffic to the database but is normally much faster as you should be doing smaller transactions. Disconnected Architecture in ADO.NET The architecture of ADO.net in which data retrieved from database can be accessed even when connection to database was closed is called as disconnected architecture. Disconnected architecture of ADO.net was built on classes connection, dataadapter, commandbuilder and dataset and dataview. Disconnected architecture is a method of retrieving a recor

HTTPHandler and HTTPModule in ASP.NET

If you want to implement pre-processing logic before a request hits the IIS resources. For instance you would like to apply security mechanism, URL rewriting, filter something in the request, etc. ASP.NET has provided two types of interception HttpModule and HttpHandler .   The web server examines the file name extension of the requested file, and determines which ISAPI extension should handle the request. Then the request is passed to the appropriate ISAPI extension.  For Example When an .aspx page is requested it is passed to ASP.Net page handler. Then Application domain is created and after that different ASP.Net objects like Httpcontext, HttpRequest, HttpResponse. HTTPModule: -    It's just like a filter. The Modules are called before and after the handler executes . -    HTTP Modules are objects which also participate the pipeline but they work before and after the HTTP Handler does its job, and produce additional services within the pipeline -