When a web page is sent to the Web Server for processing, it goes through a sequence of steps before it finally gets displayed in the Web Browser. This article discusses these series of steps and events that occur in a page life cycle in ASP.NET.
From Web Browser to IIS
When a POST request is initiated from the client side, the Web Server traps the request and it is usually routed to an .aspx web page. The request is actually routed to the HTTP Pipeline, a chain of managed objects.
After the HTTP Page handler class is identified, the ProcessRequest () method is called which eventually fires the different page events in the life cycle of a web page. The sequence of events that takes place in the life cycle of a web page in ASP.NET is:
- Page_Init
- LoadViewState
- LoadPostData
- Page_Load
- RaisePostDataChangedEvent
- RaisePostBackEvent
- Page_PreRender
- SaveViewState
- Page_Render
- Page_UnLoad
All these events are associated with their respective handlers and you can even override them to customize their default behaviour. The following section discusses each of these events in detail.
The Page Life Cycle Events Explained
Once the request for the web page arrives at the web server, the ASP.NET runtime determines whether the page needs to be parsed or whether a cached version of the page needs to be rendered to the requestor. Then the Request and the Response objects for the page are set and the page life cycle starts.
The Page_Init event is the first event to be triggered in the page life cycle. It is responsible for the initialization activities that are essential to create a page instance. In this phase of the page life cycle, all the server controls of the web page are initialized to their default values. However, it should be noted that the View State for a page is not available at this stage of the page life cycle and a server control of the page cannot access other server controls of the page at this phase.
You can use the Page_Init event to create or re-create the controls that need to be created or re-created dynamically. The following example illustrates how you can override the OnInit() method.
protected override void OnInit(EventArgs e)
{
if (Page != null)
{
Page.Trace.Write ("The OnInit method has been called");
base.OnInit(e);
Page.RegisterRequiresPostBack(this);
}
}
Next, the LoadViewState method is called. "The load view state stage only happens when the page has been posted back. During this stage the view state data saved from the previous page visit is loaded and recursively populated into the Page’s control hierarchy". This method restores the View State information of a web page that was last saved using the SaveViewState method. You can override the LoadViewState() method to get an idea on how the viewstate is actually restored.
The following code example illustrates how you can override the LoadViewState() method.
protected override void LoadViewState(Object viewState)
{
Page.Trace.Write ("The LoadViewState method has been called.");
if (viewState == null)
{
base.LoadViewState(viewState);
}
}
View State is a hidden field that is associated with every web page. It is responsible for maintaining the state of web pages between postbacks. It maintains a state of a page as it moves back and forth between the web browser at the client side and the web server at the server side. However, it should be noted that ViewState does not hold the controls, rather it holds the values of the form controls and their corresponding ID's that would otherwise be lost due to a post back because they do not post with the form. To know more on what View State in ASP.NET is and how it works, take a look at my article at the following link:
http://aspalliance.com/909
After the View State for a web page is restored, the server controls in the web page are populated with posted data, i.e., the data that was posted when the web page was sent from the we browser at the client side to the web server.
The LoadPostBackData event is fired next that processes the data that was last posted to the server for all the server controls that requires the same. Note that all controls in an ASP.NET web page is identified by a unique id. The runtime now parses the controls to match their unique ids against the Name Value Collection in the View State for the control (that has its View State enabled) and updates the control with the posted data.
The next event that gets fired is the Page_Load event that typically restores the page's control values. At this phase of the page life cycle, the web page "calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded." Typically, you bind data to the controls of your web form in this method or call methods write code that should be executed or loaded first before any other event of the web page is triggered.
A typical example of Page_Load event is cited below.
protected override void OnLoad(EventArgs e)
{
if(!IsPostBack)
{
//Code to bind static data to the controls
}
}
You can check the IsPostBack property of the web page to avoid re-setting the server control values. But why is the IsPostBack property necessary? Well, the reason is that the Page_Load event is fired with every request to the web page. Hence, this property is used to check whether the page was submitted to itself. Further, you can create dynamic controls for your web page here. You can learn more on how postback works from the article at the following link:
http://www.codeproject.com/aspnet/IsPostBack.asp
The RaisePostBackData and the RaisePostBackEvent events call their respective handlers if the request was a postback. The RaisePostBackEvent that executes next "notifies the server control that caused the postback that it should handle an incoming postback event."
The Pre_Render event is triggered next and you can perform any update operations that you require prior to saving the View State and rendering of the web page content. You can perform the update operations on the ready-to-be rendered output in the PreRender event. Use the Pre_Render event to make any last minute changes to the contents of the web page or any of its controls.
The following code snippet illustrates how you can override the OnPreRender() method.
protected override void OnPreRender (EventArgs e)
{
Page.Trace.Write ("The OnPreRender has been called.");
//Any custom code
base.OnPreRender(e);
}
The SaveViewState that is called next saves the View State for the web page and its controls in the hidden field called __viewstate that is associated with every web page. Note that the SaveViewMethod that is associated with the SaveViewState event returns a null reference if there is no view state associated with the control. Refer to the code snippet below that illustrates how you can override the SaveViewState() method.
protected override object SaveViewState ()
{
Page.Trace.Write ("The SaveViewState method has been called.");
//Write your custom code here.
return base.SaveViewState();
}
The rendering event is the next stage in the web page life cycle. This actually is not an event. Rather, it is a state of processing where the Page instance executes this method on all the controls of the web page to eventually render the web page content to the web browser at the client or the requestor side. It makes use of “a text writer that writes its output to the OutputStream of the page's Response property.” However, it should be noted that prior to rendering the web page, the view state for the web page and all its controls (provided view state for the web page and/or its controls enabled) are saved. You can trap the rendered output and make any changes on it, i.e., adding headers and footers to the rendered page, etc.
The last stage in the ASP.NET web page life cycle is the Page_UnLoad event. This event is called prior to the disposal of the web page and usually contains the code that is responsible for releasing of resources that were acquired in the earlier stages of the page life cycle. Once this is done, the web browser receives the “HTTP response packet” and the web page is displayed in the web browser. In this method, you can perform typical cleanup activities. According to MSDN, "Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed." It should be noted that you cannot make any changes to the response stream in this event as the page and its controls have already been rendered.
The web browser now receives the HTTP response packet and displays the same in the web page. This concludes the page life cycle of an ASP.NET web page.
References
Please refer to the following links for related references on this topic.
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
http://msdn2.microsoft.com/en-us/library/ms178473.aspx
http://www.15seconds.com/issue/020102.htm
http://www.aspfree.com/c/a/ASP.NET/ASP.NET-Life-Cycle-and-Best-Practices/
Conclusion
This article has had a detailed look at the series of steps that are involved in the page life cycle for an ASP.NET web page. I hope that the readers would find this article useful and I would welcome their comments and suggestions in this regard.
No comments:
Post a Comment