Software Development

ASP.NET basics: the page life cycle

This overview of the ASP.NET page life cycle covers how and when page elements are loaded and corresponding events are fired.

ASP.NET is a powerful platform for building Web applications. With any platform, it is important to understand what is going on behind the scenes to build robust applications. The ASP.NET page life cycle is a good example to explore so you know how and when page elements are loaded and corresponding events are fired.

Ready, aim, fire!

The requesting of an ASP.NET page triggers a sequence of events that encompass the page life cycle. The Web browser sends a post request to the Web server. The Web server recognizes the ASP.NET file extension for the requested page and sends the request to the HTTP Page Handler class. The following list is a sampling of these events, numbered in the order in which they are triggered.

  1. PreInt: This is the entry point of the ASP.NET page life cycle - it is the pre-initialization, so you have access to the page before it is initialized. Controls can be created within this event. Also, master pages and themes can be accessed. You can check the IsPostBack property here to determine if it is the first time a page has been loaded.
  2. Init: This event fires when all controls on the page have been initialized and skin settings have been applied. You can use this event to work with control properties. The Init event of the page is not fired until all control Init events have triggered - this occurs from the bottom up.
  3. InitComplete: This event fires once all page and control initializations complete. This is the last event fired where ViewState is not set, so ViewState can be manipulated in this event.
  4. PreLoad: This event is triggered when all ViewState and Postback data have been loaded for the page and all of its controls - ViewState loads first, followed by Postback data.
  5. Load: This is the first event in the page life cycle where everything is loaded and has been set to its previous state (in the case of a postback). The page Load event occurs first followed by the Load event for all controls (recursively). This is where most coding is done, so you want to check the IsPostBack property to avoid unnecessary work.
  6. LoadComplete: This event is fired when the page is completely loaded. Place code here that requires everything on the page to be loaded.
  7. PreRender: This is the final stop in the page load cycle where you can make changes to page contents or controls. It is fired after all PostBack events and before ViewState has been saved. Also, this is where control databinding occurs.
  8. PreRenderComplete: This event is fired when PreRender is complete. Each control raises this event after databinding (when a control has its DataSourceID set).
  9. SaveStateComplete: This is triggered when view and control state have been saved for the page and all controls within it. At this point, you can make changes in the rendering of the page, but those changes will not be reflected on the next page postback since view state is already saved.
  10. Unload: This event fires for each control and then the page itself. It is fired when the HTML for the page is fully rendered. This is where you can take care of cleanup tasks, such as properly closing and disposing database connections.

An interesting caveat of the events fired with the loading of a page is the controls within the page and their events; that is, each control has its own event life cycle. The following code provides an example of the ordering of page and a couple control events. The ASP.NET source is listed first and followed by the codebehind source. It is a basic ASP.NET 4.0 Web Form with TextBox and Literal controls. The code does not include all events, but it does provide a subset to give you a feel for how they appear. You should notice the events specified in the individual controls that ties them to code blocks.

<%@ Page Title="Home Page" Language="C#"

MasterPageFile="~/Site.master" AutoEventWireup="true"

CodeBehind="Default.aspx.cs" Inherits="WebPageLifeCycle._Default"

OnPreInit="PreInitEvent" ViewStateMode="Enabled" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent" />
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent" OnPreInit="Content_Render">

<h2>

<asp:Literal runat="server" ID="litExample" OnInit="Literal_Init"></asp:Literal>

<asp:TextBox runat="server" ID="txtExample" OnInit="Textbox_Init"></asp:TextBox>

Working with the ASP.NET Page life cycle.

</h2>

</asp:Content>
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebPageLifeCycle {

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

protected void Page_Load(object sender, EventArgs e)     {

Response.Write("Page_Load<br>");

}

protected void Page_LoadComplete(object sender, EventArgs e)  {

Response.Write("Page_LoadComplete<br>");

}

protected void Page_PreRender(object sender, EventArgs e)     {

Response.Write("Page_PreRender<br>");

}

protected void Page_Render(object sender, EventArgs e)     {

Response.Write("Page_Render<br>");

}

protected void PreInitEvent(object sender, EventArgs e)    {

Response.Write("OnPreInit<br>");

}

protected void Page_Init(object sender, EventArgs e)    {

Response.Write("Page_Init<br>");

}

protected void Literal_Init(object sender, EventArgs e)   {

Response.Write("Literal_Init<br>");

}

protected void Textbox_Init(object sender, EventArgs e)  {

Response.Write("Textbox_Init<br>");

}

protected void Page_InitComplete(object sender, EventArgs e)    {

Response.Write("Page_InitComplete<br>");

}

protected void Page_PreLoad(object sender, EventArgs e)    {

Response.Write("Page_PreLoad<br>");

}

protected void TextBox_Unload(object sender, EventArgs e)    {

// Cleanup

}  }  }

Notice the Unload event does not display anything since the Response object is not available in it, since the page and controls have been fully loaded when this event is triggered. The following lines are displayed on the page when it is loaded:

OnPreInit

Literal_Init

Textbox_Init

Page_Init

Page_InitComplete

Page_PreLoad

Page_Load

Page_LoadComplete

Page_PreRender

Know your environment

Building applications that take full advantage of the ASP.NET platform requires an understanding of the environment, and the page life cycle is just one aspect of it. By knowing when events are triggered, it helps you properly code and design an application. The Load event is the most used and demonstrated event, but others have their uses as outlined above.

Share your ASP.NET coding experience with the community in the comments.

Keep your engineering skills up to date by signing up for TechRepublic's free Software Engineer newsletter, delivered each Tuesday.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

1 comments
jasmine2501
jasmine2501

You forgot the Render event which is commonly overridden by controls developers, and you misspelled PreInit. Also, you should add some detail to this article. Anyone can get the list of events from MSDN documentation (which would be the proper source for such information) - and this article doesn't add a lot of value to the documentation because you don't provide examples. It would be helpful to provide examples of when and why you might want to respond to these events or override the methods in your own controls. Otherwise you're just creating redundant content and ruining the internet. However, this is one of the most common interview questions for .Net developers. I have been asked to regurgitate this list on many occasions. I have never been asked in-depth questions about what it means or how to use it. So I don't know, maybe the most important information IS just the list... but I would hope if you are asked this on an interview, you have the background to use it.