ASP.NET Life Cycle

Introduction

Just as in normal life, every ASP.Net control including Page has a life.

In our life we go through various events like Birth, Education, Marriage, Job and at the end death. And every event does some important task.

Similarly whenever a ASP.Net Page/Control is requested it goes through a sequence of events.

Before moving further I would like to put light on some important concepts.

How the request is handled by IIS

We give an URL to an aspx page in the browser address bar and press enter. What happens next? We get the response in terms of rendered HTML but how?

  1. We are requesting something from the browser, which means indirectly we are requesting something from the Web Server, that means IIS. IIS, based on the file extension, decides which ISAPI extension can serve the request.

    And in case of ASP.Net (.aspx) it will be aspnet_isapi_dll so the request is passed to it for processing.
     
  2. When the first request comes to the website,

    an application domain is created by the ApplicationManager class where exactly the website runs, and which creates an isolation between 2 web applications.
    Within the application domain an instance of the HostingEnvironment class is created which provides access information about the application such as the name of the folder where the application is stored.
     
  3. Next ASP.Net creates core objects like HttpContext, HttpRequest,HttpResponse.
     
  4. Finally the application starts by creating an instance of the HttpApplication Class (which can be reused for multiple requests to maximize performance).

Request processing by HttpApplication

While processing the request, HttpApplication invokes various events which include Module Events, handlers and Page Events.

The sequence is:

  1. Module events - Important events are BeginRequest, AuthenticateRequest, AuthorizeRequest, ResolveRequestCache, AcquireRequestState and PreRequestHandlerExecute.
    We can use these events when we want to inject custom Pre-Processing logic, i.e, before Page Object is created.
    (You can read more about these events here.)
     
  2. Handler Events - Once the above 6 events are fired, the ASP.NET engine will invoke the ProcessRequest event if you have implemented HttpHandler in your project. (We normally use HttpHandlers when we want to put some logic based on the file extension, such as for ImageFiles, Aspx files,...)
     
  3. Page Events - After the HttpHandler logic executes the ASP.Net Page, an object is created during which various events will be fired and the important ones are
    PreInit, Init, LoadViewState, LoadPostData, Load, ControlEvents, PreRender, SaveViewState and Render.

    We go through every event as we move further.
     
  4. Module events - Important events are PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCache and EndRequest.
    We use this when we want custom Post-Processing logic.

A developer can extend any of the events as per there convenience and logic.

A small Secret about Master Pages and Life Cycle Events

Allthough Master Pages seem like a parent they are actually a child or in short we can say they behave like a user control for pages.

<%@ Page Title="My Child Page" Language="C#" MasterPageFile="~/MyMaster.master" AutoEventWireup="true" CodeFile="ChildPage.aspx.cs" Inherits=" ChildPage " %>

All events except Init and Unload fires in the manner of from the outside to the inside.
That means PageEvent will be fired first and then masterpages then the user controls and so on.
PreInit is a kind of event which exists only for Page.
Some events get executed only if it's a postback (Full/Asynchronous).

Life Cycle Events

PreInit

The properties like IsPostBack have been set at this time.

This event will be used when we want to:

  1. Set master page dynamically.
  2. Set theme dynamically.
  3. Read or set profile property values.
  4. This event is also preferred if want to create any dynamic controls.

Init

  1. Raised after all the controls have been initialized with their default values and any skin settings have been applied.
  2. Fired for individual controls first and then for page.

LoadViewState

  1. Fires only if IsPostBack is true.
  2. Values stored in HiddenField with id as _ViewState decoded and stored into corresponding controls.

LoadPostData

Some controls like:

  1. Fires only if IsPostBack is true.
  2. Some controls like Textbox are implemented from IPostBackDataHandler and this fires only for such controls.
  3. In this event page processes postback data included in the request object pass it to the respective controls.

PreLoad

  • Used only if want to inject logic before actual page load starts.

Load

  • Used normally to perform tasks which are common to all requests, such as setting up a database query.

Control events

  1. This event is fired when IsPostBack is true.
  2. Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

PreRender

Raised after the page object has created all the controls that are required for rendering which includes child controls and composite controls.

  1. Use the event to make final changes to the contents of the page or its controls before the values are stored into the viewstate and the rendering stage begins.
  2. Mainly used when we want to inject custom JavaScript logic.

SaveViewState

  • All the control values that support viewstate are encoded and stored into the viewstate.

Render

Generates output (HTML) to be rendered at the client side.

  • We can add custom HTML to the output if we want here.

Unload

  1. Fired for individual controls first and then for page.
  2. Used to perform cleanup work like closing open files and database connections.

Reference links

http://msdn.microsoft.com/en-us/library/bb470252.aspx
http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://msdn.microsoft.com/en-us/library/9ysfzy8h(v=vs.71)