Wednesday, August 8, 2007

The ASP.NET Page lifecycle

15 Seconds : The ASP.NET Page Life Cycle When a page request is sent to the Web server, whether through a submission or location change, the page is run through a series of events during its creation and disposal. When we try to build ASP.NET pages and this execution cycle is not taken into account, we can cause a lot of headaches for ourselves. However, when used and manipulated correctly, a page's execution cycle can be an effective and powerful tool. Many developers are realizing that understanding what happens and when it happens is crucial to effectively writing ASP.NET pages or user controls. So let's examine in detail the ten events of an ASP.NET page, from creation to disposal. We will also see how to tap into these events to implant our own custom code. The events that get fired are: 1. Object Initialization 2. Load Viewstate Data 3. LoadPostData Processes Postback Data 4. Object Load 5. Raise PostBack Change Events 6. Process Client-Side PostBack Event 7. Prerender the Objects 8. ViewState Saved 9. Render To HTML 10. Disposal



Excerpt from another page I found helpful:
http://msdn2.microsoft.com/en-us/library/ms972976.aspx
So, dynamically added controls must be programmatically added to the Web page on each and every page visit. The best time to add these controls is during the initialization stage of the page life cycle, which occurs before the load view state stage. That is, we want to have the control hierarchy complete before the load view state stage arrives. For this reason, it is best to create an event handler for the Page class's Init event in your code-behind class, and add your dynamic controls there.
Note You may be able to get away with loading your controls in the Page_Load event handler and maintaining the view state properly. It all depends on whether or not you are setting any properties of the dynamically loaded controls programmatically and, if so, when you're doing it relative to the Controls.Add(dynamicControl) line. A thorough discussion of this is a bit beyond the scope of this article, but the reason it may work is because the Controls property's Add() method recursively loads the parent's view state into its children, even though the load view state stage has passed.
Shortcut Summary:
1. Object Initialization
2. Load Viewstate Data (void LoadViewState( object o ) )
3. LoadPostData Processes Postback Data
4. Object Load (void onload(EventArgs e) )
5. Raise PostBack Change Events
6. Process Client-Side PostBack Event (void RaisePostBackEvent (string eventArgument) )
7. Prerender the Objects
8. ViewState Saved (void RaisePostDataChangeEvent() )
9. Render To HTML
10. Disposal (void OnPreRender( EventArgs e ) )

No comments:

Post a Comment

Please leave your thoughts, I love hearing what you got out of the post. Spam comments will be removed.