Anda di halaman 1dari 20

ASP.

Net life cycle specifies, how:

ASP.Net processes pages to produce dynamic output

The application and its pages are instantiated and processed

ASP.Net compiles the pages dynamically


The ASP.Net life cycle could be divided into two groups:

Application Life Cycle

Page Life Cycle

ASP.Net Application Life Cycle:


The application life cycle has the following stages:

User makes a request for accessing application resource, a page. Browser sends this request to the
web server.
A unified pipeline receives the first request and the following events take place:
An object of the ApplicationManager class is created.

An object of the HostingEnvironment class is created to provide information regarding the

o
resources.
o

Top level items in the application are compiled.

Response objects are created . the application objects: HttpContext, HttpRequest and HttpResponse are
created and initialized.

An instance of the HttpApplication object is created and assigned to the request. The request is
processed by the HttpApplication class. Different events are raised by this class for processing the request.

ASP.Net Page Life Cycle:


When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is
unloaded from the memory. At each of this steps, methods and events are available, which could be overridden
according to the need of the application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except
the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page
directive. We will cover page directives and tracing under 'directives' and 'error handling'.
The page life cycle phases are:

Initialization

Instantiation of the controls on the page

Restoration and maintenance of the state

Execution of the event handler codes

Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the
page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties
with view-state data and run control behavior code.
Following are the different stages of an ASP.Net page:

Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or
there would be a cached version of the page; accordingly the response is sent
Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is
an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the
page is also set.
Page initialization . at this stage, the controls on the page are assigned unique ID by setting the
UniqueID property and themes are applied. For a new request postback data is loaded and the control properties
are restored to the view-state values.
Page load . at this stage, control properties are set using the view state and control state values.
Validation . Validate method of the validation control is called and if it runs successfully, the IsValid
property of the page is set to true.
Postback event handling . if the request is a postback (old request), the related event handler is called.
Page rendering . at this stage, view state for the page and all controls are saved. The page calls the
Render method for each control and the output of rendering is written to the OutputStream class of the Page's
Response property.
Unload . the rendered page is sent to the client and page properties, such as Response and Request
are unloaded and all cleanup done.

ASP.Net Page Life Cycle Events:


At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is
basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.
Following are the page life cycle events:

PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines
whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and
sets profile property values. This event can be handled by overloading the OnPreInit method or creating a
Page_PreInit handler.
Init . Init event initializes the control property and the control tree is built. This event can be handled by
overloading the OnInit method or creating a Page_Init handler.
InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state
tracking.
LoadViewState . LoadViewState event allows loading view state information into the controls.
LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are
processed.
PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be
handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
Load . the Load event is raised for the page first and then recursively for all child controls. The controls
in the control tree are created. This event can be handled by overloading the OnLoad method or creating a
Page_Load handler.

LoadComplete . the loading process is completed, control event handlers are run and page validation
takes place. This event can be handled by overloading the OnLoadComplete method or creating a
Page_LoadComplete handler.
PreRender . the PreRender event occurs just before the output is rendered. By handling this event,
pages and controls can perform any updates before the output is rendered.
PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event
ensures the completion of the pre-rendering phase.
SaveStateComplete . state of control on the page is saved. Personalization, control state and view state
information is saved. The HTML markup is generated. This stage can be handled by overriding the Render
method or creating a Page_Render handler.
UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all
controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as
database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a
Page_UnLoad handler.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Understanding the Page Life Cycle in ASP.NET</title>
<script language="C#" runat="server">
StringBuilder sb = new StringBuilder();
protected void Page_PreInit(object o, EventArgs e)
{
Response.Write("The Page Loaded at: " +
DateTime.Now.ToLongTimeString() + "<br /><br />");
Response.Write("<div id='mainBody'><h1>Understanding the Page Life
Cycle in ASP.NET.</h1><br /><br /><div class='divTitle'>Following is the
sequence in which the ASP.NET Page LifeCycle is executed : </div><br /><br
/>");
sb.Append("<b>Page Pre_Init</b> - Occurs at the begining of the Page
Initialization <br />");
}

public void Page_PreLoad(object sender, EventArgs e)


{

sb.Append("<b>Page Pre Load </b>- Occurs before the Load Event


<br />");
}

public void Page_InitComplete(object sender, EventArgs e)


{
sb.Append("<b>Page Init Complete </b>- Occurs when the Page
Initialization is Complete <br />");
}

void Page_LoadComplete(object sender, EventArgs e)


{

sb.Append("<b>Page Load Complete </b>- Occurs at the end of Load


Stage of the Page Life Cycle. <br />");
}
protected void Page_Init(object sender, EventArgs e)
{
sb.Append("<b>Page Init </b>- Occurs when the Server Control is
Initialized. It is the first step in the ASP.NET Page Life Cycle <br />");
}
protected void Page_Load(object sender, EventArgs e)
{
sb.Append("<b>Page Load </b>- Occurs when the Server Control is
Loaded in the Page Object <br />");
}

void Page_PreRenderComplete(object sender, EventArgs e)


{
sb.Append("<b>Page Pre Render Complete </b>- Occurs before the Page
Content is Rendered <br />");
}

void Page_PreRender(object sender, EventArgs e)

{
sb.Append("<b>Page Pre Render </b>- Occurs after the Server Controls
is Loaded in the Page but before the Rendering</div> <br />");
Response.Write(sb.ToString());
}

/// <summary>
/// This is the event when the page is unloaded from the server memory and
ready to be returned to the client,
/// Here the response is not available, so you cannot modify the Response
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Page_Unload(object sender, EventArgs e)
{
}
</script>
<style type="text/css">
.button
{
border-radius:4px 4px 4px 4px;
height:30px;
padding:5px;
font-size:14px;
background-color:#6ca21e;
color:#FFFFFF
}
body
{
background-color:#32373a;
color:#FFFFFF;
}
#mainBody

{
background-color:#FFFFFF;
height:100%;
color:#32373a;
}
.divTitle
{
width: 450px;
height: 30px;
background-color: #fdd136;
font-size: 14px;
}
</style>
</head>
<body>
<form id="form1" runat="server">

</form>
</body>
</html>

ASP.Net life cycle specifies, how:

ASP.Net processes pages to produce dynamic output

The application and its pages are instantiated and processed

ASP.Net compiles the pages dynamically

The ASP.Net life cycle could be divided into two groups:


1.

Application Life Cycle

2.

Page Life Cycle

ASP.Net Application Life Cycle:


The application life cycle has the following stages:

User makes a request for accessing application resource, a page. Browser sends
this request to the web server.

A unified pipeline receives the first request and the following events take place:

An object of the ApplicationManager class is created.


An object of the HostingEnvironment class is created to provide
information regarding the resources.
Top level items in the application are compiled.

Response objects are created . the application objects: HttpContext, HttpRequest


and HttpResponse are created and initialized.

An instance of the HttpApplication object is created and assigned to the request.


The request is processed by the HttpApplication class. Different events are raised by
this class for processing the request.

ASP.Net Page Life Cycle:


When a page is requested, it is loaded into the server memory, processed and sent to the
browser. Then it is unloaded from the memory. At each of this steps, methods and events
are available, which could be overridden according to the need of the application. In
other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the
components on the page, except the directives are part of this control tree. You can see
the control tree by adding trace= "true" to the Page directive. We will cover page
directives and tracing under 'directives' and 'error handling'.
The page life cycle phases are:

Initialization

Instantiation of the controls on the page

Restoration and maintenance of the state

Execution of the event handler codes

Page rendering

Understanding the page cycle helps in writing codes for making some specific thing
happen at any stage of the page life cycle. It also helps in writing custom controls and
initializing them at right time, populate their properties with view-state data and run
control behavior code.
Following are the different stages of an ASP.Net page:

Page request . when ASP.Net gets a page request, it decides whether to parse
and compile the page or there would be a cached version of the page; accordingly
the response is sent

Starting of page life cycle . at this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of the
page is set to true. The UICulture property of the page is also set.

Page initialization . at this stage, the controls on the page are assigned unique
ID by setting the UniqueID property and themes are applied. For a new request
postback data is loaded and the control properties are restored to the view-state
values.

Page load . at this stage, control properties are set using the view state and
control state values.

Validation . Validate method of the validation control is called and if it runs


successfully, the IsValid property of the page is set to true.

Postback event handling . if the request is a postback (old request), the related
event handler is called.

Page rendering . at this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Page's Response property.

Unload . the rendered page is sent to the client and page properties, such as
Response and Request are unloaded and all cleanup done.

ASP.Net Page Life Cycle


Events:
At each stage of the page life cycle, the page raises some events, which could be coded.
An event handler is basically a function or subroutine, bound to the event, using
declarative attributes like Onclick or handle.
Following are the page life cycle events:

PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack
property and determines whether the page is a postback. It sets the themes and
master pages, creates dynamic controls and gets and sets profile property values.
This event can be handled by overloading the OnPreInit method or creating a
Page_PreInit handler.

Init . Init event initializes the control property and the control tree is built. This
event can be handled by overloading the OnInit method or creating a Page_Init
handler.

InitComplete . InitComplete event allows tracking of view state. All the controls
turn on view-state tracking.

LoadViewState . LoadViewState event allows loading view state information into


the controls.

LoadPostData . during this phase, the contents of all the input fields defined
with the <form> tag are processed.

PreLoad . PreLoad occurs before the post back data is loaded in the controls. This
event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.

Load . the Load event is raised for the page first and then recursively for all child
controls. The controls in the control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load handler.

LoadComplete . the loading process is completed, control event handlers are run
and page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler.

PreRender . the PreRender event occurs just before the output is rendered. By
handling this event, pages and controls can perform any updates before the output
is rendered.

PreRenderComplete . as the PreRender event is recursively fired for all child


controls, this event ensures the completion of the pre-rendering phase.

SaveStateComplete . state of control on the page is saved. Personalization,


control state and view state information is saved. The HTML markup is generated.
This stage can be handled by overriding the Render method or creating a
Page_Render handler.

UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the
UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is
done and all resources and references, such as database connections, are freed. This
event can be handled by modifying the OnUnLoad method or creating a
Page_UnLoad handler.

Events and Life Cycle of a Page (ASP.Net 1.x VS ASP.Net 2.0):

In the ASP.NET runtime the life cycle of a page is marked by a series of events.
In ASP.NET 1.x, based on user interaction a page request is sent to the Web
server. The event that is initiated by the page request is Init. After the Init
event, Load event is raised. Following the Load event,PreRender event is
raised. Finally, the Unload event is raised and an output page is returned to the
client.

ASP.NET 2.0 adds a few new events to allow you to follow the request
processing more closely and precisely.
These new events are discussed in the following table.

New Events in ASP.NET 2.0:


Events

Description

PreInit

This occurs before the page begins initialization. This is the first
event in the life of an ASP.NET 2.0 page.

InitComplete

This occurs when the page initialization is completed.

PreLoad

This occurs immediately after initialization and before the page


begins loading the state information.

LoadComplete

This occurs at the end of the load stage of the page's life cycle.

PreRenderComplet This occurs when the pre-rendering phase is complete and all
e
child controls have been created. After this event, the
personalization data and the view state are saved and the page
renders to HTML.

This new features enable developer to dynamically modify the page


output and the state of constituent controls by handling these events.

When a page request is sent to the Web server, the page is run through a
series of events during its creation and disposal.
In this article, I will discuss in detail the ASP.NET page life cycle Events

(1) PreInit
The entry point of the page life cycle is the pre-initialization phase called
"PreInit". This is the only event where programmatic access to master
pages and themes is allowed. You can dynamically set the values of
master pages and themes in this event. You can also dynamically create
controls in this event.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
using
using
using
using
using
using

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

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


{
protected void Page_PreInit(object sender, EventArgs e)
{
// 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.
}

(2)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.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected void Page_Init(object sender, EventArgs e)
{
// Raised after all controls have been initialized and any skin settings have been
applied.
// Use this event to read or initialize control properties.
}

(3)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
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected void Page_InitComplete(object sender, EventArgs e)
{
// Raised by the Page object. Use this event for processing tasks that require all
initialization be complete.
}

(4)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
Loads ViewState : ViewState data are loaded to controls
Note : 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.
Loads Postback data : postback data are now handed to the page controls
Note : 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. Hence, the page fires the LoadPostData event
and parses through the page to find each control 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.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected override void OnPreLoad(EventArgs e)
{
// Use this event if you need to perform processing on your page or control before
the Load event.
// Before the Page instance raises this event, it loads view state for itself and all
controls, and
// then processes any postback data included with the Request instance.
}

(5)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.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected void Page_Load(object sender, EventArgs e)
{
// The Page calls the OnLoad event method on the Page, then recursively does
the same for each child
// control, which does the same for each of its child controls until the page and all
controls are loaded.
// Use the OnLoad event method to set properties in controls and establish
database connections.
}

(6)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, for example.
These are the events, the code for which is written in your code-behind
class(.cs file).
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected void Button1_Click(object sender, EventArgs e)
{
// This is just an example of control event.. Here it is button click event that caused
the postback
}

(7)LoadComplete
This event signals the end of Load.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page

protected void Page_LoadComplete(object sender, EventArgs e)


{
// Use this event for tasks that require that all other controls on the page be
loaded.
}

(8)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.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected override void OnPreRender(EventArgs e)
{
// Each data bound control whose DataSourceID property is set calls its DataBind
method.
// The PreRender event occurs for each control on the page. Use the event to make
final
// changes to the contents of the page or its controls.
}

(9)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.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected override void OnSaveStateComplete(EventArgs e)
{
// 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.
}

(10)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.
Note: Right click on the web page displayed at client's browser and view
the Page's Source. You will not find any aspx server control in the code.
Because all aspx controls are converted to their respective HTML
representation. Browser is capable of displaying HTML and client side
scripts.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
// Render stage goes here. This is not an event

(11)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.
EXAMPLE : Override the event as given below in your code-behind cs file
of your aspx page
protected void Page_UnLoad(object sender, EventArgs 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.
// 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.
}
}

The life cycle starts when a user requests a web page through his/her browser. The Web
server than process the page through a sequence of steps before response is sent back
to the user's browser. The steps are as:

1. Page Request
2. Start
3. Page Initialization
4. Load
5. Validation
6. PostBack Event Handling
7. Render
8. Unload
The below figure shows the Page Life Cycle of an ASP.NET and its
controls

Page Request
The page request occurs before the page life cycle begins. When a user
requests the page, ASP.NET determines whether the page needs to be
parsed and compiled (therefore beginning the life of a page), or whether a
cached version of the page can be sent in response without running the
page.
Start
In the start step, 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.
Page Initialization

During page initialization, controls on the page are available and each
control's UniqueID are generated but not their properties. Any themes
are also applied to the page.
Developers have access to the Init, InitComplete and PreLoad methods
in this stage. The methods are as follows:

Init: This event is raised after all controls have been initialized and any skin
settings have been applied. This event is used to read or initialize control
properties.

InitComplete: The Page object raises this event. This event is used for
processing tasks that require completion of all initialization.

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.

Load
During load, if the current request is a postback, control properties are
loaded with information recovered from view state and control state.
The OnLoad event method is fired during this stage.
This is where you will want to set properties for all of the server controls
on your page, request query strings, and establish database connections.
Validation
During validation, the Validate method of all validator controls is called,
which sets the IsValid property of individual validator controls and of the
page.
PostBack Event Handling
If the request is a postback, any event handlers are called. The event
handling for server controls occurs during this stage.
Render
During rendering, view state is saved to the page and then the page calls
on each control to contribute its rendered output to the OutputStream of
the page's Response property. Render is not really an event. The HTML of
the page and all controls are sent to the browser for rendering.
Unload

Unload is called when the page has been fully rendered, sent to the client,
and is ready to be discarded. At this point, page properties such
as Response and Request are unloaded and any cleanup is performed.
The cleanup includes routines such as closing database connections and
file streams, or, event logging and other tasks.
Conclusion
When a Web page is requested, the server creates objects associated with
the page and all of its child controls objects and uses these to render the
page to the browser. Once the final stage is complete, the web server
destroys these objects, to free up resource to handle additional request.

PreInit:
You can:

Check for the IsPostBack property to determine whether this is the first time
the page is being processed.
Create or recreate dynamic controls.
Set master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
If Request is postback:
The values of the controls have not yet been restored from view state.
If you set control property at this stage, its value might be overwritten in the
next event.
Init:
In the Init event of the individual controls occurs first, later the Init event of
the Page takes place.
This event is used to initialize control properties.
InitComplete:
Tracking of the ViewState is turned on in this event.
Any changes made to the ViewState in this event are persisted even after the
next postback.
PreLoad:
This event processes the postback data that is included with the request.
Load:
In this event the Page object calls the OnLoad method on the Page object
itself, later the OnLoad method of the controls is called.
Thus Load event of the individual controls occurs after the Load event of the
page.
ControlEvents:
This event is used to handle specific control events such as
a Button controls Click event or a TextBoxcontrols TextChanged event.
In case of postback:

If the page contains validator controls, the Page.IsValid property and the
validation of the controls takes place before the firing of individual control events.
LoadComplete:
This event occurs after the event handling stage.
This event is used for tasks such as loading all other controls on the page.
PreRender:
In this event the PreRender event of the page is called first and later for the
child control.
Usage:
This method is used to make final changes to the controls on the page like
assigning the DataSourceId and calling the DataBind method.
PreRenderComplete:
This event is raised after each control's PreRender property is completed.
SaveStateComplete:
This is raised after the control state and view state have been saved for the
page and for all controls.
RenderComplete:
The page object calls this method on each control which is present on the
page.
This method writes the controls markup to send it to the browser.
Unload:
This event is raised for each control and then for the Page object.
Usage:
Use this event in controls for final cleanup work, such as closing open
database connections, closing open files, etc.

Anda mungkin juga menyukai