Wednesday, March 2, 2011

ASP.Net Page Life Cycle events

A page in an ASP.NET application consists of several server controls. These are the fundamental building blocks of an ASP.NET application. The Life cycle of an ASP.NET page, depends on whether the page is requested for the first time or it is a postback. Postback is a process by which a page can request for itself.


When the Page is requested for the first time


The Life Cycle of a page when requested for the first time:

Initializing: During this phase, the server creates an instance of the server control

Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.

PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.

Saving: During this phase, the state information of the control is saved. For example, if a value is set for the control during the Load event, it is embedded in the HTML tag that will be returned to the browser.

Rendering: During this phase, the server creates the corresponding HTML tag for the control.

Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.

Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control

Life cycle when the page processed during a postback event

The processing sequence in which a page is processed during a postback event is:

Initializing: During this phase, the server creates an instance of the server control

Loading view state: During this phase, the view state of the control posted by the client is reloaded into the new instance of the control.

Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.

Loading the postback data: During this phase, the server searches any data corresponding to the control that is loaded in the data posted by the client.

PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.

Saving state: During this phase, the change in the state of control between the current request and the previous request of the page is saved. For each change, the corresponding event is raised. For example, if the text of a textbox is changed, the new text is saved and a text_change event is raised.

Rendering: During this phase, the server creates the corresponding HTML tag for the control.

Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.

Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control

The events associated with the relevant page cycle phases are:
  • Page Initialization: Page_Init
  • View State Loading:LoadViewState
  • Postback data processing: LoadPostData
  • Page Loading: Page_Load
  • PostBack Change Notification: RaisePostDataChangedEvent
  • PostBack Event Handling: RaisePostBackEvent
  • Page Pre Rendering Phase: Page_PreRender
  • View State Saving: SaveViewState
  • Page Rendering: Page_Render
  • Page Unloading: Page_UnLoad





The following are the main ten steps in the ASP.NET page life cycle.


1. Object Initialization


A page's controls (and the page itself) are first initialized in their raw form. By declaring your objects within the constructor of your C# code-behind file, the page knows what types of objects and how many to create. Once you have declared your objects within your constructor, you may then access them from any sub class, method, event, or property. However, if any of your objects are controls specified within your ASPX file, at this point the controls have no attributes or properties. It is dangerous to access them through code, as there is no guarantee of what order the control instances will be created (if they are created at all). The initialization event can be overridden using the OnInitmethod. 

2. Load Viewstate Data


After the Init event, controls can be referenced using their IDs only (no DOM is established yet for relative references). At LoadViewState event, the initialized controls receive their first properties: viewstate information that was persisted back to the server on the last submission. The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request. As you can see, this is a giant leap forward from the old ASP 3.0 techniques of maintaining state. This event can be overridden using theLoadViewState method and is commonly used to customize the data received by the control at the time it is populated.  

3. LoadPostData Processes Postback Data

During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. When a page submits a form, the framework will implement theIPostBackDataHandler interface on each control that submitted data. The page then fires the LoadPostData event and parses through the page to find each control that implements this interface and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. Extra steps are taken by the framework to ensure each ID is unique in situations, such as several custom user controls existing on a single page. After the LoadPostData event triggers, theRaisePostDataChanged event is free to execute (see below). 


4. Object Load 

Objects take true form during the Load event. All object are first arranged in the page DOM (called the Control Tree in ASP.NET) and can be referenced easily through code or relative position (crawling the DOM). Objects are then free to retrieve the client-side properties set in the HTML, such as width, value, or visibility. During Load, coded logic, such as arithmetic, setting control properties programmatically, and using the StringBuilder to assemble a string for output, is also executed. This stage is where the majority of work happens. TheLoad event can be overridden by calling OnLoad. 


5. Raise PostBack Change Events


As stated earlier, this occurs after all controls that implement theIPostBackDataHandler interface have been updated with the correct postback data. During this operation, each control is flagged with a Boolean on whether its data was actually changed or remains the same since the previous submit. ASP.NET then sweeps through the page looking for flags indicating that any object's data has been updated and fires RaisePostDataChanged. TheRaisePostDataChanged event does not fire until all controls are updated and after the Load event has occurred. This ensures data in another control is not manually altered during the RaisePostDataChanged event before it is updated with postback data. 


6. Process Client-Side PostBack Event

After the server-side events fire on data that was changed due to postback updates, the object which caused the postback is handled at theRaisePostBackEvent event. The offending object is usually a control that posted the page back to the server due to a state change (with autopostbackenabled) or a form submit button that was clicked. There is often code that will execute in this event, as this is an ideal location to handle event-driven logic. The RaisePostBackEvent event fires last in the series of postback events due to the accuracy of the data that is rendered to the browser. Controls that are changed during postback should not be updated after the executing function is called due to the consistency factor. That is, data that is changed by an anticipated event should always be reflected in the resulting page. TheRaisePostBackEvent can be trapped by catching RaisePostBackEvent. 


7. Prerender the Objects 

The point at which the objects are prerendered is the last time changes to the objects can be saved or persisted to viewstate. This makes the PreRender step a good place to make final modifications, such as changing properties of controls or changing Control Tree structure, without having to worry about ASP.NET making changes to objects based off of database calls or viewstate updates. After the PreRender phase those changes to objects are locked in and can no longer be saved to the page viewstate. The PreRender step can be overridden using OnPreRender.


8. ViewState Saved


The viewstate is saved after all changes to the page objects have occurred. Object state data is persisted in the hidden <input> object and this is also where object state data is prepared to be rendered to HTML. At the SaveViewStateevent, values can be saved to the ViewState object, but changes to page controls are not. You can override this step by using SaveViewState. 

9. Render To HTML


The Render event commences the building of the page by assembling the HTML for output to the browser. During the Render event, the page calls on the objects to render them into HTML. The page then collects the HTML for delivery. When the Render event is overridden, the developer can write custom HTML to the browser that nullifies all the HTML the page has created thus far. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser. Changes can still be made at this point, but they are reflected to the client only.  

10. Disposal

After the page's HTML is rendered, the objects are disposed of. During theDispose event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. You can override Dispose, as well as Render by setting the appropriate selection in the object parameter.

Interview Questions

1. Explain the AutoPostBack feature in ASP.NET?

AutoPostBack allows a control to automatically postback when an event is fired. For eg: If we have a Button control and want the event to be posted to the server for processing, we can set AutoPostBack = True on the button.

2. What are the different code models available in ASP.NET 2.0?
There are 2 code models available in ASP.NET 2.0. One is the single-file page and the other one is the code behind page.
3. Which base class does the web form inherit from?
Page class in the System.Web.UI namespace.

4. Explain the ViewState in ASP.NET?
Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. The information is stored in HTML hidden fields. In other words, it is a snapshot of the contents of a page.
You can disable viewstate by a control by setting the EnableViewState property to false.
5. What does the EnableViewState property signify?
EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.

6. Explain the Event Life cycle of ASP.NET 2.0?
The events occur in the following sequence. Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :
PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.
Init – Each control in the control collection is initialized.
Init Complete* - Page is initialized and the process is completed.
PreLoad* - This event is called before the loading of the page is completed.
Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.
LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.
PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.
PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.
Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.
The events marked with * have been introduced in ASP.NET 2.0.

4 comments: