……………………………………………….Expertise in .NET Technologies

ASP.NET Page Life Cycle Overview

Posted by Ravi Varma Thumati on February 2, 2010

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run any control behavior code. (The life cycle of a control is based on the page life cycle, but the page raises more events for a control than are available for an ASP.NET page alone.)

The ASP.NET Page Life Cycle Events:

As ASP.NET processes a page through its stages, various events are raised for the page and its related controls. You write code to handle these events and thus respond to various actions related to the processing of a page. For example, you might wish to write code that gets called when a page is first loaded to determine if the user is requesting the page or posting back to the server. This is a common scenario. When a page is first requested you often have to initialize data and controls. However, when it posts back you do not wish to run this code.

Another common example is when a user clicks a button. You want to respond to the click event for that button only. Knowing which events are called in what order is important to making sure your code executes properly and can be debugged. Here are the sequences of events that are raised whenever you request an ASP.NET page.

  1. PreInit
  2. Init
  3. InitComplete
  4. PreLoad
  5. Load
  6. LoadComplete
  7. PreRender
  8. PreRenderComplete
  9. SaveStateComplete
  10. Render
  11. Unload

PreInit: This is the first real event you might handle for a page. You typically use this event only if you need to dynamically (from code) set values such as master page or theme.

This event is also useful when you are working with dynamically created controls for a page. You want to create the controls inside this event.

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.

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: This event fires after each control has been initialized. You can use this event to change initialization values for controls.

InitComplete: Raised once all initializations of the page and its controls have been completed.

PreLoad: This event fires before view state has been loaded for the page and its controls and before PostBack processing. This event is useful when you need to write code after the page is initialized but before the view state has been wired back up to the controls.

Load: The page is stable at this time; it has been initialized and its state has been reconstructed. Code inside the page load event typically checks for PostBack and then sets control properties appropriately.

The page’s load event is called first. Then, the load event for each child control is called in turn (and their child controls, if any). This is important to know if you are writing your own user or custom controls.

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, for example.

In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

LoadComplete: At this point all controls are loaded. If you need to do additional processing at this time you can do so here.

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.

Before this event occurs:

  • The Page object calls EnsureChildControls for each control and for the page.
  • 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.

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. This is useful if you need to write processing that requires the view state to be set.

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. This method is useful if you are writing your own custom control. You override this method to control output for the control.

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.

If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method.

UnLoad: This event is used for cleanup code. You use it to release any managed resources in this stage. Managed resources are resources that are handled by the runtime, such as instances of classes created by the .NET common language runtime.

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.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

The following figure illustrates how the server controls on an ASP.NET page is processed by the server:

First time instance:

Post back Instance:

Life Cycle Events and the Global.asax file

During the application life cycle, the application raises events that you can handle and calls particular methods that you can override. To handle application events or methods, you can create a file named Global.asax in the root directory of your application.

If you create a Global.asax file, ASP.NET compiles it into a class derived from the HttpApplication class, and then uses the derived class to represent the application.

An instance of HttpApplication processes only one request at a time. This simplifies application event handling because you do not need to lock non-static members in the application class when you access them. This also allows you to store request-specific data in non-static members of the application class. For example, you can define a property in the Global.asax file and assign it a request-specific value.

ASP.NET automatically binds application events to handlers in the Global.asax file using the naming conventionApplication_event, such as Application_BeginRequest. This is similar to the way that ASP.NET page methods are automatically bound to events, such as the page’s Page_Load event.

The Application_Start and Application_End methods are special methods that do not represent HttpApplicationevents. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

The following table lists some of the events and methods that are used during the application life cycle. There are many more events than those listed, but they are not commonly used.

Event or method Description
Application_Start Called when the first resource (such as a page) in an ASP.NET application is requested. The Application_Start method is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.

You should set only static data during application start. Do not set any instance data because it will be available only to the first instance of the HttpApplication class that is created.

Application_event Raised at the appropriate time in the application life cycle, as listed in the application life cycle table earlier in this topic.

Application_Error can be raised at any phase in the application life cycle.

Application_EndRequest is the only event that is guaranteed to be raised in every request, because a request can be short-circuited. For example, if two modules handle the Application_BeginRequest event and the first one throws an exception, theApplication_BeginRequest event will not be called for the second module. However, the Application_EndRequest method is always called to allow the application to clean up resources.

HttpApplication.Init Called once for every instance of the HttpApplication class after all modules have been created.
Dispose Called before the application instance is destroyed. You can use this method to manually release any unmanaged resources. For more information, see Cleaning Up Unmanaged Resources.
Application_End Called once per lifetime of the application before the application is unloaded.

Compilation Life Cycle

When the first request is made to an application, ASP.NET compiles application items in a specific order. The first items to be compiled are referred to as the top-level items. After the first request, the top-level items are recompiled only if a dependency changes. The following table describes the order in which ASP.NET top-level items are compiled.

Item Description
App_GlobalResources The application’s global resources are compiled and a resource assembly is built. Any assemblies in the application’s Bin folder are linked to the resource assembly.
App_WebResources Proxy types for Web services are created and compiled. The resulting Web references assembly is linked to the resource assembly if it exists.
Profile properties defined in the Web.config file If profile properties are defined in the application’s Web.config file, an assembly is generated that contains a profile object.
App_Code Source code files are built and one or more assemblies are created. All code assemblies and the profile assembly are linked to the resources and Web references assemblies if any.
Global.asax The application object is compiled and linked to all of the previously generated assemblies.

Once the application’s top level items have been compiled, ASP.NET compiles folders, pages, and other items as needed. The following table describes the order in which ASP.NET folders and items are compiled.

Item Description
App_LocalResources If the folder containing the requested item contains an App_LocalResources folder, the contents of the local resources folder are compiled and linked to the global resources assembly.
Individual Web pages (.aspx files), user controls (.ascx files), HTTP handlers (.ashx files), and HTTP modules (.asmx files) Compiled as needed and linked to the local resources assembly and the top-level assemblies.
Themes, master pages, other source files Skin files for individual themes, master pages, and other source code files referenced by pages are compiled when the referencing page is compiled.

Compiled assemblies are cached on the server and reused on subsequent requests and are preserved across application restarts as long as the source code is unchanged.

Because the application is compiled on the first request, the initial request to an application can take significantly longer than subsequent requests. You can precompile your application to reduce the time required for the first request.


One Response to “ASP.NET Page Life Cycle Overview”

  1. […] ASP.NET Page Life Cycle Overview […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: