Loading ...

ASP.NET Page life cycle

Who is online?  0 guests and 0 members
home  »  articles  »  ASP.NET Page Life Cycle

ASP.NET Page Life Cycle

(195475)
0
/5
Avg: 0/5: (0 votes)
Published: 6/18/2009 by  Raghav Khunger

 

 

The first step that takes place is Page Request. The page request occurs before the page life cycle begins. Each time a request arrives at a Web server for an ASP.NET Web page, the first thing the Web server does is hand off the request to the ASP.NET engine. The ASP.NET engine then takes the request through a pipeline composed of numerous stages. At the end of the pipeline, a class corresponding to the requested ASP.NET Web page is instantiated and the ProcessRequest() method is invoked.This life cycle of the ASP.NET page starts with a call to the ProcessRequest() method. This method begins by initializing the page's control hierarchy. When the page is requested ASP.NET determines whether the page needs to be parsed and compiled or whether the already present cached version of the page is to be sent in response without running the page. If the page needs to be compiled a dynamic compiled class is generated that represents this ASPX page. This compiled class is then stored in the “Temporary ASP.NET Files” folder. As long as the ASPX page is not modified (or the application itself is restarted, in which case the request will actually be the first request and then the generation of the class will occur again), then future requests to the ASPX page will be served by the same compiled class. In this stage page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set. The life cycle ends by handing off the Web page's HTML markup to the Web server, which sends it back to the client that requested the page.

PreInit
The entry point of the page life cycle is the pre-initialization phase called “PreInit”. Note that this event is not recursive, meaning that it is accessible only for the page itself and not for any of its child controls.

• Use this event for the following:
• Check the IsPostBack property to determine whether this is the first time the page is
• being processed.
• Create or re-create dynamic controls.
• Set a master page dynamically.
• Set the Theme property dynamically.
• Read or set profile property values.
• Note: If the request is a postback, the values of the controls have not yet been restored
• from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init
During this phase, the server creates an instance of the server control. The “Init” event is fired reclusively for the page itself and for all the child controls in the hierarchy (which is created during the creation of the compiled class, as explained earlier). Note that against many developers’ beliefs, the event is fired in a bottom to up manner and not an up to bottom within the hierarchy.A page's controls (and the page itself) are first initialized in their raw format. At this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInit method.

Bottom To Up hierarchy
To understand this I have taken one Default.aspx page and one WebUserControl.ascx usercontrol .Both of them have OnInit method.

ASPX Code of default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Src="~/UserControls/WebUserControl.ascx" TagName="DemoControl" TagPrefix="DemoControlPrefix" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <DemoControlPrefix:DemoControl ID="DemoControlID" runat="server" />
    </div>
    </form>
</body>
</html>

It's Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        Response.Write("Page OnInit is Fired");
    }
}

 

ASCX Code of Web user control

<%@
Control Language="C#" AutoEventWireup="true"
CodeFile="WebUserControl.ascx.cs"
Inherits="UserControls_WebUserControl" %>


It's Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControls_WebUserControl : System.Web.UI.UserControl
{
    protected override void OnInit(EventArgs e)
    {
        Response.Write("WebUserControl  OnInit is Fired. <br/>");
    }

}

Now when you will run the default.aspx page you will see this output:
You saw from above that this event is fired from inner most to the outer most (ie Page).

LoadViewState(Only on postbacks)

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
    }

This event happens only at postbacks.After the Init event, controls can be referenced using their IDs only (no DOM is established yet for relative references). At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request. This event can be overridden using the LoadViewState method and is commonly used to customize the data received by the control at the time it is populated.This is a recursive event, much like the “Init” event. In this event, the Viewstate which has been saved in the __VIEWSTATE during the previous page visit (via the SaveViewState event) is loaded and then populated into the control hierarchy.When you will open view source of the page in the browser . You will find the Viewstate here like this


<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZMay7eOSHw5VVezZs0hebeVuXJhi" />

LoadPostBack(Only on postbacks)
This event happens only at postbacks.During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. When a page submits a form, the framework will implement the IPostBackDataHandler interface on each control that submitted data.

What is Post Data
When the form was submitted some controls (for example TextBox1) will submit their values as a {ID, value} pairs we call this the Post Data.The page then fires the LoadPostData event and parses through the page to find each control that implements this interface and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. Extra steps are taken by the framework to ensure each ID is unique in situations, such as several custom user controls existing on a single page. This is a recursive event much like the “Init” event. During this event, the posted form data is loaded into the appropriate controls. For example, assume that, on your form, you had a TextBox server control, and you entered some text inside the TextBox and posted the form. The text you have entered is what is called postback data. This text is loaded during the LoadPostbackdata event and handed to the TextBox. This is why when you post a form, you find that the posted data is loaded again into the appropriate controls. This behavior applies to most controls like the selected item of a drop down list or the “checked” state of a check box, etc.A very common conceptual error is the thought that Viewstate is responsible for preserving posted data. This is absolutely false; Viewstate has nothing to do with it. If you want a proof, disable the Viewstate on your TextBox control or even on the entire page, and you will find that the posted data is still preserved.

Load
During this phase, the instance of the control is loaded onto the page object in which it is defined.




View state information is available at this point. Objects take true form during the Load event. All object are first arranged in the page DOM (called the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. This event is recursive much like the “Init” event. 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. That is because the LoadViewState and the LoadPostbackdata events are fired upto this time.

Up To Bottom hierarchy
To understand this I have taken one Default.aspx page and one WebUserControl.ascx user control .Both of them have Page_Load method.

Aspx Code of default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Src="~/UserControls/WebUserControl.ascx" TagName="DemoControl" TagPrefix="DemoControlPrefix" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <DemoControlPrefix:DemoControl ID="DemoControlID" runat="server" />
    </div>
    </form>
</body>
</html>


It’s Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Page  Page_Load is Fired.<br/>");
    }

}

ASCX Code of web user control

<%@
Control Language="C#" AutoEventWireup="true"
CodeFile="WebUserControl.ascx.cs"
Inherits="UserControls_WebUserControl" %>

It's Code Behind 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControls_WebUserControl : System.Web.UI.UserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("WebUserControl  Page_Load is Fired.");
    }

}


Now when you will run the default.aspx page you will see this output:
You saw from above that this event is fired from outermost (i.e. Page) to the inner most (i.e. User Control).

RaisePostBackEvent
This occurs after all controls that implement the IPostBackDataHandler interface have been updated with the correct postback data. This event handles the user action that caused the Postback. This event occurs after all controls that implement the IPostBackDataHandler interface have been updated with the correct postback data. During this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP.NET then sweeps through the page looking for flags indicating that any object's data has been updated and fires RaisePostDataChanged. The RaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. After the server-side events fire on data that was changed due to postback updates, the object which caused the postback is handled at the RaisePostBackEvent event. The offending object is usually a control that posted the page back to the server due to a state change (with autopostback enabled) or a form submit button that was clicked. The RaisePostBackEvent that executes next “notifies the server control that caused the postback that it should handle an incoming postback event.”There is often code that will execute in this event, as this is an ideal location to handle event-driven logic. For example If the visitor clicks Button1, then Button1_Click is usually called to perform its function

    protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
    {
        base.RaisePostBackEvent(sourceControl, eventArgument);
    }


Prerender
The application is about to render the Page object. The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender. During this event

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


each data bound control whose DataSourceID property is set calls its DataBind method.

SaveViewState
The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden <input> object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not. You can override this step by using SaveViewState.

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

Render
The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only. The Render event can be overridden. The Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render themselves into HTML. The page then collects the HTML for delivery.

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

Unload
The page is unloaded from memory at this point.

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

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, or finishing up logging or other request-specific tasks. Note: During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

 

Comments (5)

Very Nice Article.
8/13/2009
 · 
 
by
Really gr8 article as per to undersatand event cycle and implement it in your performance based application.
8/20/2009
 · 
 
by
Dorababu
Dorababu M said:

Superb One

2/10/2011
 · 
 
by
srikanthvarma

Nice Article....but would have been much better if the description goes with an example..

5/2/2011
 · 
 
by
rohitkakria
rohit kakria said:

Superb ....

Rohit

5/26/2011
 · 
 
by

Confirm

Product Spotlight

ASP.NET Hosting Spotlight

Most Recent Articles

 

Product Spotlight

ASP.NET Hosting Spotlight

Quick Vote

What kind of email newsletter would you prefer to receive from CodeAsp.Net?