Page Events: Order and PostBack
page 1 of 1
Published: 17 Oct 2003
Unedited - Community Contributed
Abstract
This article lists the complete lifecycle of ASP.NET Pages, including the postback sequence, and explains which method or event to use in common scenarios.
by Paul Wilson
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 51950/ 96

Page Events: Order and PostBack

Initialization

The first method that executes when a page is requested is always the constructor. You can initialize many of the custom properties or objects in the page at this time, although there are a few limitations since the page hasn't fully initialized yet. In particular, you will have to use the HttpContext.Current object to access the Request QueryString, Form, and Cookies collections, along with the Cache object. However, there is no way to access the Session collection within the constructor.

The next method that executes is the AddParsedSubObject method, which actually adds all the individual controls that make up a page into the control collection tree. This method is typically overridden by some of the advanced page template solutions in order to add the page contents into a particular control in the page template. This method is recursively called on all children controls for each page control, and each of these controls is initialized at this time, starting with the innermost.

The next method that executes is the DeterminePostBackMode method of the page class. This method allows you to affect the value of IsPostBack and all the related events, which might be useful if you need to load ViewState from a database for a redirect, since we will see that ViewState is only restored when IsPostBack is actually true. Just return null to force non-PostBack and return Request.Form to force a PostBack. This is not recommended, except in special cases, since it affects other events too.

The page's OnInit method is executed next, which is typically the first method used. By the time this occurs, all the controls defined in your page will be initialized, which means that all the original values specified in the aspx page will be applied. However, ViewState and any posted values will not have been applied to controls yet, so anything that changed as a result of the code or user will not yet be restored. This is usually the best place to create, and recreate, any dynamic controls used.

Restore and Load

The next method, LoadPageStateFromPersistenceMedium, only executes for PostBacks. This method is overridden when you have altered how the page's ViewState was saved, later in the SavePageStateToPersistenceMedium, when using Session or Custom Stores. The default implementation assumes ViewState is a Base64 encoded hidden form field, but this can be changed in these two methods using code found in this related article. Note that this method does not actually restore ViewState to the page or its controls.

After ViewState is retrieved, the next method, LoadViewState, restores it to the page, and then recursively to each control and their children, but again only on PostBacks. After this executes, each control will now be restored to the state it was last time, but user posted values will still not be applied, since this is not part of ViewState. The best use of this method is to restore any dynamic controls you created in events, based on values you must manually save in ViewState, which is now available to use.

The next method, ProcessPostData, only executes for PostBacks, and it is not able to be overridden, since it is a private method implemented by the base page class. This method finally restores the user's posted form values by matching up controls with the names of the values, which means your page will finally be fully restored. The only catch is that dynamic controls must be created prior to this page method. This is also the method that records changes in values for the changed events later.

The page's OnLoad method is executed next, which is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method, and all the control's methods will be executed to catch up, including ViewState, but posted values would not be.

Raised Events

The next method, ProcessPostData, is actually a second pass of the earlier method, which still only executes for PostBacks and is not overridable since private method. This second pass always seems a little odd when you first notice it in the page trace, but it occurs because dynamic controls recreated in OnLoad need their posted values. Any controls that are dynamically created after this method, while having ViewState restored, will not get their posted values nor be able to trigger any changed events.

The next method, RaiseChangedEvents, also occurs only for PostBacks, and it too is a private method that is implemented in the base page class that cannot be overridden. This is the time in the page lifecycle that the changed events are actually raised, based on the differences that ProcessPostData noted before and after posted values. You may also want to call Validate and check the value of IsValid, if not already. There is no guarantee about the order that multiple changed events will be raised.

The next method, RaisePostBackEvent, also occurs only for PostBacks, and it too is a private method that is implemented in the base page class that cannot be overridden. This is where the event that actually submitted the form, unless using AutoPostBack, is actually raised, typically a button, or a control that uses javascript to submit. If not manually called already, Validate is also called, when using some Validators. Note a bug in IE sometimes allows the Enter key to submit without triggering an event.

The page's OnPreRender method is executed next, which is typically the last chance to affect the page and its controls before it is rendered to the client's browser. You can also create dynamic controls in this method, and all the control's methods will be executed to catch up, including ViewState, but the earlier private methods will not receive another pass, meaning no posted values are restored and no events. This is a good place to catch a PostBack without an event due to the bug noted in IE.

Save and Render

The next method that executes, regardless whether PostBack or not, is SaveViewState which recursively runs for each control and their children, to create the ViewState. ViewState basically stores any property values that are different from the original values that are defined in the aspx page, whether changed in the code or by the user. Note that control values are saved according to their location in the control tree, so ViewState can get corrupted if dynamic controls are later added in wrong positions.

The next method, SavePageStateToPersistenceMedium, actually saves the page ViewState. This method is overridden, along with LoadPageStateFromPersistenceMedium, to save the ViewState either to Session or a Custom Store, instead of using the hidden field. This is useful for low bandwidth cases, and Session is the default for Mobile Pages. See the code found in this related article for details of using these two methods, and note that a bug in ASP.NET requires a __VIEWSTATE field to be sent, even if empty.

The page's Render method is executed next, which recursively runs for each control and their children, to actually create and send the resulting html to the browser. This method is used in some page template solutions to add common headers and footers to the page without using server controls, which always have a little extra overhead. Note that changes made here must be pure html, since controls are done at this time. You can capture the html output using StringBuilder, StringWriter, and HtmlTextWriter.

The very last method to be executed is OnUnload, which also calls the Dispose method. This method gives you a chance to cleanup any unmanaged resources used in the page, typically things like closing any open files or database connections open earlier. Note that this method runs only after the page has been sent to the client's browser, so it will only affect server objects, and it will not show up in a trace of the page. And that's the page lifecycle -- everything runs all over again with each new request.

Listing 1: Page Events Summary

MethodPostBackControls

ConstructorAlwaysAll
AddParsedSubObjectAlwaysAll
DeterminePostBackModeAlwaysPage
OnInitAlwaysAll

LoadPageStateFromPersistenceMediumPostBackPage
LoadViewStatePostBackAll
ProcessPostData1PostBackPage
OnLoadAlwaysAll

ProcessPostData2PostBackPage
RaiseChangedEventsPostBackPage
RaisePostBackEventPostBackPage
OnPreRenderAlwaysAll

SaveViewStateAlwaysAll
SavePageStateToPersistenceMediumAlwaysPage
RenderAlwaysAll
OnUnloadAlwaysAll

Author Bio

Paul Wilson is a software architect in Atlanta, currently with PRG-Schultz. He specializes in Microsoft technologies, including .NET, C#, ASP, SQL, COM+, and VB. His WilsonWebForm Control allows Multiple Forms and Non-PostBack Forms in ASP.NET. He is a Microsoft MVP in ASP.NET and is also recognized as an ASPInsider. He is a moderator on Microsoft's ASP.NET Forums, as well as one of the top posters. He is holds the MCSD, MCAD, MCDBA, and MCSE certifications. Please visit his website, www.WilsonDotNet.com, or email him at Paul@WilsonDotNet.com.


User Comments

Title: hol   
Name: hola
Date: 2012-05-18 5:43:57 PM
Comment:
hola
Title: test   
Name: test
Date: 2012-04-16 8:10:06 AM
Comment:
no comments
Title: thank   
Name: henry
Date: 2011-01-08 8:44:43 PM
Comment:
thank for this article.
Title: .NET, C#, ASP, SQL, COM+, and VB. His WilsonWebForm Control allows Multiple Forms and Non-PostBack Forms in ASP.NET. He is a Microsoft MVP in ASP.NET   
Name: architect in Atlanta, currently with PRG-Schultz. He specializes in Microsoft technologies, including .NET, C#, ASP, SQL
Date: 2009-12-15 1:26:46 PM
Comment:
The next method that executes, regardless whether PostBack or not, is SaveViewState which recursively runs for each control and their children, to create the ViewState. ViewState basically stores any property values that are different from the original values that are defined in the aspx page, whether changed in the code or by the user. Note that control values are saved according to their location in the control tree, so ViewState can get corrupted if dynamic controls are later added in wrong positions.The next method that executes, regardless whether PostBack or not, is SaveViewState which recursively runs for each control and their children, to create the ViewState. ViewState basically stores any property values that are different from the original values that are defined in the aspx page, whether changed in the code or by the user. Note that control values are saved according to their location in the control tree, so ViewState can get corrupted if dynamic controls are later added in wrong positions. The next method that executes, regardless whether PostBack or not, is SaveViewState which recursively runs for each control and their children, to create the ViewState. ViewState basically stores any property values that are different from the original values that are defined in the aspx page, whether changed in the code or by the user. Note that control values are saved according to their location in the control tree, so ViewState can get corrupted if dynamic controls are later added in wrong positions. The next method that executes, regardless whether PostBack or not, is SaveViewState which recursively runs for each control and their children, to create the ViewState. ViewState basically stores any property values that are different from the original values that are defined in the aspx page, whether changed in the code or by the user. Note that control values are saved according to their location in the control tree, so ViewState can get corrupted if dynamic contr
Title: Mr   
Name: Robert Earl Hazelett
Date: 2009-02-11 2:56:28 PM
Comment:
I wrote and installed the above websit, but on initialization it does not appear onscreen in the sequence I want. Your article does not explain how to make that happen. You see, I am brand new at this and therefore dumb as a stump. Can you recommend some book that will educate me on how to make the screen apeear in ANY sequence I want?

Thank you,

Robert Earl Hazelett
Title: some one says,....... you Are Good Man   
Name: zubair
Date: 2008-07-31 12:55:42 AM
Comment:
Hi
This Is A Vewry Cool Link Site,

It Helps Many New Commers, Thanks

Zubair From {Lahore Pakistan}

+ 92 333 473 8642
Title: You are good, Man   
Name: Leib Avraham
Date: 2008-07-19 9:16:49 AM
Comment:
This your article and ViewState one helped me to understand
the issue
Title: fall in love   
Name: Mohammad Javed
Date: 2008-06-21 7:52:48 AM
Comment:
excellent article
Title: Much easy   
Name: mitesh kumar
Date: 2008-06-20 1:45:36 AM
Comment:
I read this topic and found that it is simplest than any one .
Title: Mind Blowing   
Name: mike hussey
Date: 2008-04-15 2:54:28 AM
Comment:
excellent to read...pls keep some worked exampls....
Title: Good, but something missing   
Name: Tomas
Date: 2008-04-10 12:27:46 PM
Comment:
Good and straightforward written, just missing info about same event ordering between Page / (User)Control. Because Init() event is first called for other controls and at the end for page, but Load() event is called first for page and then for other controls.
Title: Thanks   
Name: Remmod
Date: 2008-02-18 11:17:23 AM
Comment:
Thanks very much
Title: PreLoad?   
Name: E
Date: 2008-02-11 7:04:33 PM
Comment:
Where's the PreLoad event?
Title: helpfull   
Name: bruce
Date: 2007-12-11 2:11:01 AM
Comment:
very helpfull...
thanks
Title: I have a question   
Name: Denis
Date: 2007-11-23 5:23:03 AM
Comment:
Nice work. I would also like to know if there are any events when the page is left or closed
Title: Awesome stuff!!!!!!   
Name: Fatima
Date: 2007-11-14 4:58:39 AM
Comment:
Very helpful..thanks:;)
Title: Great work !!!   
Name: Mohd Imran
Date: 2007-10-12 7:56:00 AM
Comment:
A really nice article for clear understanding of Page Events.
Title: WOW!   
Name: Tim
Date: 2007-08-15 5:27:01 PM
Comment:
By far this is the best (both simple and complete) resource I have found regarding a aspx page and the events that "fire" as pages are "hit".
Title: Excellent   
Name: Sasikumar
Date: 2007-06-27 8:32:28 AM
Comment:
The Best one
Title: Thanks   
Name: halphe
Date: 2007-06-13 2:30:29 AM
Comment:
Thank you very much.This is a good article for everyone who want to resolve problems.
Title: harsha   
Name: vardhan
Date: 2007-05-28 8:12:43 AM
Comment:
it is well
Title: Soooooooooo Helpful   
Name: Lu
Date: 2007-05-04 12:21:44 PM
Comment:
The best clear simple artical for page life cycle.
Title: Simple & Understandable   
Name: Venkata kiran kumar
Date: 2007-03-16 2:29:45 AM
Comment:
Very Help full ..
Title: One of the most understandable write-ups about ASP.NET   
Name: Rick P
Date: 2007-02-21 6:40:06 PM
Comment:
Extremely helpful!
Title: Excellent   
Name: Manitra
Date: 2007-01-30 12:26:44 PM
Comment:
As you can see, 4 years later, your article is still the best one about the page lifecycle in asp.net. It really helped me to resolved most of the viewstate problems I had.

Congratulation.
Title: HelpFul   
Name: aVN-Developer
Date: 2006-12-01 10:59:13 PM
Comment:
Thank you
Title: Best   
Name: Prakash Patel
Date: 2006-11-21 8:47:43 AM
Comment:
Good Article..Provides In depth knowledge.
Title: very good analysis   
Name: venki
Date: 2006-11-20 10:52:56 AM
Comment:
very nice, thanks for the good one
Title: great   
Name: Ashin
Date: 2006-09-22 10:07:36 AM
Comment:
helped me
Title: Excellent article   
Name: Hari Pillai
Date: 2006-06-26 10:31:44 PM
Comment:
Thanks for the article. Excellent!!
Title: Good Article - Keep it Up   
Name: Pankaj Sharma
Date: 2006-05-18 2:42:37 AM
Comment:
Provides basic details which really pleased me while reading this article. Author Knows what really a reader should desire about page events.

Thanks by heart.
Title: Very Pleased   
Name: Lee
Date: 2006-05-11 1:18:55 PM
Comment:
After looking for a more accurate (complete!!!)description of the event life cycle of the page object this is FLAWLESS! All the other articles I have read fail in that purpose.
Title: Good work   
Name: girishkumar.k
Date: 2006-03-28 10:59:54 AM
Comment:
Great Article,you h ave done great Job.It helps to all .NET
Professionals who are in thrust of Knowledge.Try to Give Description for each event.
Title: post back commands   
Name: raja mohamed
Date: 2006-03-22 5:12:20 AM
Comment:
I found this article to be very helpful.
Title: Question   
Name: Ryan Kaelin
Date: 2006-01-18 10:16:53 AM
Comment:
Having an issue, and since this is the best resource I've found yet, I thought I'd ask you.

I have a page with usercontrols within usercontrols within usercontrols. At some point in the workflow, the user enters a number into a text box and clicks a button that causes a post back.

I then have to dynamically load that many usercontrols into a panel on that usercontrol. Fine. That part works great. But when I post back to capture the values entered in those dynamically created controls, there are no controls in the panel.Controls collection.

After playing around with all the various events, I found if I place a method in the overridden OnInit event, those controls will exist - only after I post back twice. Once to add the controls to my object's collection curing the Raised Events section, and the second time, the OnInit reads that my object's collection has items in it, and renders the controls.

Any idea how to accomplish dynamically added controls at the 'Raised Events' section and have them be available on the NEXT postback?
Title: Great   
Name: Grant
Date: 2005-10-11 7:23:04 PM
Comment:
Great write up very intuitive
Title: Good article   
Name: Dhana
Date: 2005-07-12 6:59:56 PM
Comment:
it is good article to read especially for those learning ASP.Net technology.
Title: Great article   
Name: Russ
Date: 2005-05-24 2:16:20 AM
Comment:
Very good article. Clears up probably the biggest unknown in the ASP.NET world.

As you say the "second pass of ProcessPostData" occurs to set the posted data of dynamically created controls. Is there any way to prevent this? I'm creating a dynamic checkbox in a Page_Load, settings its ID and setting checked=false. But the ProcessPostData comes along a returns it to its value from the post data! What are the options? Creating the control in PreRender instead?
Title: Powerfull   
Name: Phil
Date: 2005-04-26 1:52:10 PM
Comment:
Short, precise and complete thanx it went straight to my favourates.
Title: Mr   
Name: Stephen Smith
Date: 2005-04-15 8:44:12 AM
Comment:
Good article well written
Title: Good   
Name: pradeep
Date: 2005-03-08 7:16:31 AM
Comment:
Really Good Gives Indepth Information
Title: Agreed   
Name: art
Date: 2005-02-17 1:17:42 PM
Comment:
I would have to agree with the comments posted so far - this is good stuff. Helpful in designing management of dynamic controls. Thanks.
Title: KiqAss article   
Name: zep
Date: 2005-01-25 6:54:58 AM
Comment:
Awesome concepts.. Thanks.. This is exactly what I was looking for...
Title: Architect/Developer   
Name: Hermann Klinke
Date: 2005-01-18 1:18:41 PM
Comment:
Thank you so much for this great article. This is what I was looking for (as a ASP.NET beginner).
Title: Quite useful   
Name: Rajorshi
Date: 2005-01-09 8:38:00 PM
Comment:
It's quite a good article. Detailed description of a Page's lifecycle. Nice one! - Cheers.
Title: Good Job   
Name: brightheroes
Date: 2004-11-18 3:29:13 AM
Comment:
Good Job!
Title: Very Insightful   
Name: Tod Birdsall
Date: 2004-11-15 6:01:42 PM
Comment:
I found this article to be very helpful.

Keep up the good work.
Title: Nice   
Name: Sunil Phani Manne
Date: 2004-10-01 7:37:58 AM
Comment:
I found it to be very useful.
Title: Good   
Name: ruchi
Date: 2004-09-25 2:36:28 AM
Comment:
Good Article..Provides In depth knowledge.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-10-07 7:52:31 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search