Page Lifecycle
Let''s take a moment to consider the series of events that occur whenever an ASP.NET page is requested, how it is loaded, when the events are raised, and when controls are rendered. When you create a page, you are really creating a new Page object (instantiating a new instance of the Page class). The Page class defines a series of methods, properties, and events that are available to all ASP.NET pages. When loading a page for the first time, you might, for example, want to preload the Page object controls with values from a database, or set property values of various controls on the page dynamically.Let''s quickly look at the order of events that happen on the server every time a page is requested. This is shown in Figure 10-5:
Figure 10-5
When a page is requested, the server runs through the page lifecycle as it prepares the page for the browser. Let''s quickly run through the main items in this list:Init event: This is the first stage in the page lifecycle. If you so want, you could add code to the Page_Init() method to handle this event. The code in this method will then be processed before any code in the Page_Load() method and before any event handlers are processed. You can use it to initialize variables or objects that you may need later.Load ViewState and Postback data: This stage is at which any data sent back from the client related to the state of the page and the information being requested is handled.Load event: The Page_Load() method handles the Load event of the page and usually contains any code that needs to be processed each time the page is loaded. We''ll soon look at this in more detail.Handle control events: From the clicking of a button to the selection changing in a listbox, this is the stage where any event handler method is processed. We''ve seen many of these events in action already and we''ll soon see many more. Remember that at this point any code in your Page_Load() method will have already been run.PreRender event: The Page_PreRender() method is processed when this event is fired. You can add code here to perform any last minute processing after all the control events are processed. We''ll see an example of how to use this event in the next chapter.Render method called: At this stage, the ASP.NET processor starts converting the ASP.NET code into HTML. It''s at this stage that the HTML sent to the browser is produced. It''s possible to add code to cause controls to be rendered differently, thereby customizing their appearance. We''ll look at this in detail when we learn more about creating custom server controls in Chapter 13.Unload event: This stage is used for last minute cleanup of any objects that you may have used, such as database connections. We''ll see an example of this in just a moment. Note that because this event is handled after the render method is called, you can''t now affect the appearance of the page.Dispose method called: This is where the page object that was processed is removed from the .NET managed memory space on the Web server. This method is called behind the scenes when any .NET object falls out of scope and is no longer needed. Therefore, once a page is sent to the client, the server can forget about how that page was rendered on that occasion and free up memory.The following code listings provide an overview of some methods that are commonly overridden in an ASPX Page object implementation that allow you to perform processing during the various stages of the page''s lifetime.
Page_Load()
The Page_Load() method is invoked anytime the ASP.NET page is requested – in other words, when the page is loaded for the first time, refreshed, or reloaded. The following is a sample implementation of the Page_Load() method:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// First time page loads
// perform initialization here!
}
}
The most interesting part of the preceding listing is the reference to the Page object''s IsPostBack property. The IsPostBack property is significant because it can be used to distinguish whether a page is being loaded for the very first time, or if it''s being loaded as the result of a postback. If a Button control was clicked, a Click event would be raised and the form data would be posted (sent) back to the server – hence the term postback. You have already used this technique several times in the past few chapters.
The most common uses of implementing the Page_Load() method in your ASPX pages are to:Check whether this is the first time the page is being processed, or to perform processing after the page is refreshedPerform data binding the first time the page is processed, or re-evaluate data binding expressions on subsequent round trips to, for example, display the sorted data differentlyRead and update control propertiesYou''ll often use the if (!Page.IsPostBack) construct in your pages when binding data to controls on a page. Minimizing the number of times you query a database is essential for a site with good performance, and in many cases you will only want to bind data once because the data is stored in the page''s ViewState.
Event Handling
The next major part in the lifecycle of a page is the event handling stage. After an ASPX page is loaded and displayed, additional event handlers are invoked when control events are raised. For example, after a user clicks an ASP.NET Button control, the Click event is raised, which causes a postback to the server so that the event can be handled. If an event handler is written and assigned to process the Click event for that particular control, it will be invoked whenever the Button control is clicked.Not all controls perform this type of automatic posting-back to the server when an event is raised. For example, the TextBox control does not, by default, post back notification to the server when its text changes. Similarly, the ListBox and CheckBox server controls do not, by default, post back event notifications to the server every time their selection state changes. For these controls, the AutoPostBack property (which can be set to either true or false ) needs to be explicitly set to true in the control''s declaration (or set programmatically within the code) to enable automatic post back of events (or state changes) to the server for processing.Note
If you create an ASP.NET Web control that performs server-side processing whenever the control''s state changes (such as when a CheckBox is checked), and you don''t seem to be getting the results you expect, check if the control has an AutoPostBack property and whether it is set to true . This property typically defaults to false if not explicitly declared when the control is defined.
Page_Unload()
Page_Unload() serves the opposite purpose to the Page_Load() method. The Page_Unload()
method is used to perform any cleanup just before the page is unloaded. You would want to implement the Page_Unload() method in cases where any of the following actions need to be performed:Closing filesClosing database connectionsAny other cleanup or discarding of server-side objects or resourcesThe following is an example implementation of the Page_Unload() method:
void Page_Unload(object sender, EventArgs e)
{
// Perform any post-load processing here!
}
One thing to note is that the unloading of a page doesn''t occur when you close the browser or move to another page. The Page_Unload() event occurs after the page has been processed by ASP.NET and before it''s sent to the browser, by which time it is too late to do anything that will affect the appearance of the page.Right then – now that we''ve spent time looking at how pages and basic controls work, let''s put it together by starting our Wrox United application.