Resources

Events raised in the ASP.NET life cycle

Pages (and controls within them) have a life cycle.

ASP.NET raises events at different stages in the life cycle.

Application Life Cycle

In production environments ASP.NET applications run within a web server, usually IIS. Following stages make up life cycle of ASP.NET app running on II 7.5:

  1. User make request for page
  2. Request routed to processing pipeline, which forwards it to ASP.NET runtime
  3. ASP.NET create instance of ApplicationManager class. This class represent the .NET framework domain used to execute application requests. Application domain isolates global variables from other apps, allows each app to load / unload as required
  4. Instance of HostingEnvironment class created - provides access to items within hosting environment, e.g. directories
  5. ASP.NET creates instances of core objects used to process request - includes HttpContext, HttpRequest, HttpResponse
  6. Instance of HttpApplication created (or reused). This acts as base for sites Global.asax file. Use this class to trap events raised when app starts or stops. When instance of class created, modules such as SessionStateModule are also configured.
  7. ASP.NET processes requests through the HttpApplication pipeline. Pipeline includes set of events for validating requests, mapping URLs, accessing cache, etc.

Responding to Application Events

HttpApplication provides several events that can be handled that are raised when ASP.NET raised events at the application level. Include actions such as initialising variable values at app start, logging app requests, handling app level errors, etc. These events do not work on a per-user level.

Events automatically mapped if follow the Application_ naming structure. Common eventsL

Others include; Application_BeginRequest, Application_EndRequest, ResolveRequestCache, etc.

Implement these events by adding a global.asx (known as Global Application class) file to project. Created automatically if use ASP.NET Web site template, otherwise

  1. Right click website project file and select Add New Item
  2. Select Global Application Class

Reading & Writing Application State Data

Access app-level state data via the Application collection (which is an instance of the HttpApplicationState class). Multiple webpages may be running concurrently on several threads, therefore must lock Application object when performing updates to it,e.g.

Application.Lock();

Application["PageRequestCount"] = ((int)Application["PageRequestCount"]) + 1;

Application.UnLock();

Do not need to lock Application when initialising variables within Application_Start.

Where possible use Cache object instead.

Life Cycle of ASP.NET Webpage

Starts when user requests webpage through a browser.

Server creates objects associated with webpage, along with all child control objects and uses these to render page.

Server then destroys these objects to free up resources.

Page Life cycle Events

As page progress through the life cycle ASP.NET raised various events. Write code to handle these events, e.g. when page loaded event handling code may determine if user is requesting page or posting back to server - if former then initialise controls and their data.

Common events that are raised when page is processed:

Event Description
PreInit Usually used to set values such as master page or theme. Also useful when working with dynamically created controls for page without master page - create controls inside this event.
Init Fires after all controls initialised. Can be used to change initialisation values. Use this event to dynamically add controls to content page.
InitComplete Raised when initialisation of page and its controls is complete. Fired before view state has been loaded and postback processing commenced. Useful when writing code after page has initialised but before view state has been wired up to the controls.
PreLoad Raised after view state has been loaded and page has processed post back data.
Load Page is stable - its has been initialised and sate reconstructed. Code inside this event usually checks for postback and sets control properties appropriately. Page load event called first. Then for each child control in turn.
Control (postback) event(s)   ASP.NET calls any events on page (or its controls) that caused postback to occur, e.g. a button click.
LoadComplete All controls have been loaded - perform any additional processing that is required!
PreRender Allows for final changes to page and controls. Takes place after all regular postback events have taken place. Occurs before ViewState has been saved, so any changes made here will be saved.
SaveStateComplete Any changes to page or controls at this point or beyond are ignored.
Render This is a method of the page and its controls - it is not an event. ASP.NET calls this method on the pages controls to get their output. Generates client side HTML, Dynamic HTML and script required to display control on browser. Useful if writing own custom control.
Unload Used for clean up code. Use it to manually release resources - a process that is rarely required.

 

Adding controls at runtime

Add via Page.PreInit event - if not using master pages.

Add via Page.Init event - if using master pages and are adding control to a content page.

If add control in Init or Load will need to manually call Control.ApplyStyleSheetSkin method.

Follow these high level steps:

  1. Add Panel (or PlaceHolder) control to ASPX page
  2. In Page.PreInit or Page.Init create instance of control
  3. Set control properties - if need to access control from another method then ensure ID property is set
  4. Add event handlers to control (if necessary)
  5. Add control to Panel.Controls collection.

Control instances created in Page_Load or Page_Init will not be available in event handlers. Will need to find control in Panel.Controls collection and cast it to the correct type.

Control Life Cycle Events

Share common life cycle with Page class.

A controls event occurs during the same event for its parent - when page execute load event it then does so for each child control. Each control that contains other child controls executes the load event for each child control.

This is only true for controls added at design time, those added dynamically will have their events fired sequentially until its events have caught up to the current stage for its container.

Creating Event Handlers

For a controls default event, e.g. for Page it is Load, for Button it is Click, double click control in Visual Studio page designer and event handler will be created.

For non-default Page events:

  1. Right click webpage in Solution Explorer, choose View Markup. Verify page's AutoEventWireup property in @ Page directive is true.
  2. Right click webpage and choose View Code. Within the partial class add the appropriate handler, e.g.
private void Page_Init(object sender, EventArges e) { ... } 

Handling events for controls is easier - use property window for control to generate event stub.

Controlling automatic Postback

Some controls always cause postback when specific event occurs, e.g. the Button controls click event.

Others do not, e.g. TextBox contains default event of TextChanged which by default does not cause automatic postback. The event is not lost, ASP.NET raises the event during next postback that does occur - usually when user clicks on a button.

Any postponed event executes before the actual event causing the postback.

The AutoPostBack property on a control is used to change whether the controls default event causes an automatic postback.

Downloads