Page event (Init,load,prerender) execution order

Source: Internet
Author: User

Brief introduction

Each request for a microsoft®asp.net page processed by microsoft®internet Information Services (IIS) is handed over to the ASP. NET HTTP pipeline. The HTTP pipeline consists of a series of managed objects that process the request sequentially and convert the URL to plain HTML text. The entry for the HTTP pipeline is the HttpRuntime class. The ASP. NET structure creates an instance of this class for each AppDomain in the worker process. (Note that the worker process maintains a specific AppDomain for each ASP that is currently running.) )

The HttpRuntime class obtains the HttpApplication object from the internal pool and arranges this object to handle the request. The main task of the HTTP Application Manager is to find the class that will actually process the request. When you request an. aspx resource, the handler is the page handler, which is an instance of the class that inherits from the page . The association relationship between the resource type and the handler type is stored in the application's configuration file. Rather, the default mapping set is defined in the section of the Machine.config file. However, the application can customize its own list of HTTP handlers in the local Web. config file. The following line of code is used to define an HTTP handler for an. aspx resource.

<add verb= "*" path= "*.aspx" type= "System.Web.UI.PageHandlerFactory"/>                        

The extension can be associated with a handler class, and more is associated with the handler factory class. In all cases, the HttpApplication object responsible for processing the request gets an object that implements the IHttpHandler interface. If the associated resource/class is parsed according to an HTTP handler, the returned class will implement the interface directly. Additional steps are required if the resource is bound to a handler factory. The handler factory class implements the IHttpHandlerFactory interface, and the gethandler method of this interface returns an IHttpHandler-based object.

How does the HTTP runtime end this loop and process the page request? The ProcessRequest method is very important in the IHttpHandler interface. By calling this method on the object representing the requested page, the ASP. NET structure initiates the process that will generate the browser output.

The real Page class

The type of HTTP handler for a particular page depends on the URL. When the URL is first called, a new class is built, which is dynamically compiled into an assembly. The result of examining the parsing process for the. aspx resource is the source code of the class. The class is defined as part of the namespace ASP and is given a name that simulates the original URL. For example, if the end point of the URL is page.aspx, then the name of the class is ASP. Page_aspx. However, the name of the class can be controlled programmatically by setting the ClassName property in the @Page directive.

The base class for the HTTP handler is Page. This class defines the smallest collection of methods and properties that are shared by all page handlers. The Page class implements the IHttpHandler interface.

In many cases, the base class of the actual handler is not the Page, but the other class. This can happen, for example, if code separation is used. Code separation is a development technique that isolates the code required for a page into separate C # and Microsoft Visual basic®.net classes. The Code of the page is a set of event handlers and helper methods that really determine the behavior of the page. This code can be defined inline with the <script runat=server> tag, or placed in an external class (a code-splitting class). A code-splitting class is a class that inherits from the Page and uses an extra method, and is specified as the base class for the HTTP handler.

In another case, the HTTP handler is not Page -based, that is, in the <pages> section of the application configuration file, contains the redefinition of the PageBaseType property.

<pages pagebasetype= "classes.mypage, MyPage"/>                        

The PageBaseType property indicates the type and assembly of the base class that contains the page handler. This class, derived from Page , can automatically give a custom method and set of properties for the handler extension.

The life cycle of a page

When the HTTP page handler class is fully recognized, the ASP. NET runtime invokes the handler's ProcessRequest method to process the request. Typically, you do not need to change the implementation of this method because it is provided by the Page class.

This implementation begins with the frameworkinitialize method called to build the control tree for the page. The frameworkinitialize method is a protected virtual member of the TemplateControl class (ThePage itself is exported from this class). All handlers that are dynamically generated for the. aspx resource will overwrite frameworkinitialize. In this method, the entire control tree of the page is built.

Next,ProcessRequest the page through various stages: Initialize, load view state information and postback data, load user code for the page, and perform postback server-side events. After that, the page enters display mode: Collects the updated view state, generates the HTML code, and then sends the code to the output console. Finally, the page is uninstalled and the request is processed.

In each phase, the page triggers a few events that can be intercepted and processed by WEB controls and user-defined code. Some of these events are private to the embedded control and therefore cannot be processed at the. aspx code level.

The page to handle a particular event should explicitly register a suitable handler. However, for backwards compatibility with earlier Visual Basic programming styles, ASP. NET also supports the form of an implicit event hook. By default, the page tries to match the specific method name to the event, and if the implementation matches, it is considered to be the handler for the matching event. ASP. NET provides a specific recognition of six method names, which are Page_Init,Page_Load,page_databind,Page_PreRender , and page_unload. These methods are considered to be handlers for the corresponding events provided by the Page class. The HTTP runtime automatically binds these methods to page events, so that developers no longer have to write the required glue code. For example, if a method named Page_Load is bound to a page's Load event, the following code is omitted.

This. Load + = new EventHandler (this. Page_Load);                        

Automatic recognition of a particular name is controlled by the AutoEventWireup property of the @Page directive. If this property is set to False, all applications that handle the event need to explicitly connect to the page event. Pages that do not use auto-binding events are slightly better performing because there is no need to match names and events. Note that all Microsoft Visual studio®.net projects are created with the AutoEventWireup property disabled. However, the default setting for this property is true, that is, methods such as Page_Load are recognized and bound to the associated event.

The following table lists the stages of the execution of the page in order, with flags executed by some application-level events and/or protected and overwritten methods.

Table 1:asp.net key events in the life of a page

Stage Page Events methods that can be overridden
Page initialization Init
Load View state LoadViewState
Handling Postback data LoadPostData method in any control that implements the IPostBackDataHandler interface
Load page Load
Postback change Notification RaisePostDataChangedEvent method in any control that implements the IPostBackDataHandler interface
Handling Postback Events Any postback event defined by the control RaisePostBackEvent method in any control that implements the IPostBackDataHandler interface
Previous stage of page display PreRender
Save View state SaveViewState
Show Page Render
Uninstall page Unload

Some of the stages listed above are not visible at the page level and are meaningful only to the author of the server control and to the developer who will create the class exported from page . Init,Load,PreRender,Unload, plus all postback events defined by the embedded control, make up the various stage markers for outgoing pages.

Various stages of execution

The first stage in the page life cycle is initialization. The flag for this stage is the Init event. This event is triggered on the application after the control tree for the page is successfully created. In other words, when the Init event occurs, all controls that are statically declared in the. aspx source file are instantiated and take their own default values. Control can intercept the Init event to initialize all the settings required for the lifetime of the incoming WEB request. For example, a control can load an external template file or set a handler for an event. Note that the view state information is not yet available.

After initialization, the page frame loads the view state of the page. View state is a collection of name/value pairs in which the control and the page itself store all the information that must always be valid for all WEB requests. The view state represents the calling context of the page. Typically, it contains the state of the control when the page was last processed on the server. The first time a page is requested in a session, the view state is empty. By default, view state is stored in a hidden field that is silently added to the page, and the name of the field is __viewstate. By overriding the LoadViewState method (the protected, overriding method of thecontrol Class), the component developer can control how view state is stored and how the content of the view state is mapped to the internal state.

Some methods (such as loadpagestatefrompersistencemedium and their corresponding savepagestatetopersistencemedium), Can be used to load and save view state to other storage media, such as a session, database, or server-side file. Unlike LoadViewState , the above method can only be used in classes that are exported from Page .

After the view state is stored, the state of the control in the page tree is the same as the last time the page was displayed in the browser. The next step is to update their status to join the client's changes. Processing the postback data stage gives the control an opportunity to update its state to accurately reflect the state of the corresponding HTML element for the client. For example, the HTML element corresponding to the server's TextBox control is <input type=text>. In the postback data phase, the TextBox control retrieves the current value of the <input> tag and uses that value to refresh its internal state. Each control extracts values from the postback data and updates its own partial properties. The TextBox control will update its Text property, and the CheckBox control will refresh its Checked property. The correspondence between server controls and HTML elements can be found by their IDs.

At the end of the processing postback data stage, the state of all controls on the page will update the previous state with the changes that were entered by the client. At this point, the Load event is triggered on the page.

There may be controls on the page that need to complete a particular task when one of its sensitive properties is modified in two different requests. For example, if the text of a TextBox control is modified on the client, this control will trigger the TextChanged event. Each control can decide to trigger the corresponding event when one or more of its properties are modified to the value entered by the client. Controls implement the IPostBackDataHandler interface for controls that are critical to these changes, and the LoadPostData method for this interface is called immediately after the Load event. By encoding the LoadPostData method, the control verifies that a critical change has occurred since the last request and triggers its own change event.

A critical event in the page life cycle is the event that is called to execute server-side code that is associated with events that are triggered by the client. When the user clicks the button, the page is sent back. The collection of postback values includes the ID of the button that initiated the entire operation. If the control implements IPostBackEventHandler interfaces such as buttons and link buttons, the page framework calls the RaisePostBackEvent method. The behavior of this method depends on the type of control. In the case of buttons and link buttons, this method looks for the Click event handler and runs the related delegate.

After the postback event is processed, the page can be displayed. The sign of this stage is the PreRender event. Controls can take this time to perform the update operations that need to be performed before the view state is saved and the output is displayed. The next state is SaveViewState, in which all controls and the page itself will update the contents of their ViewState collection. Then, you get the serialized, hashed, BASE64 encoded view state, and this view state is associated with the hidden field __viewstate.

You can change the display mechanism of individual controls by overriding the Render method. This method accepts HTML writer objects and uses this object to accumulate all the HTML text that you want to generate for the control. The default implementation of the Page class's Render method includes recursive calls to all member controls. For each control, the page calls the Render method and caches the HTML output.

The last flag in the life of the page is the Unload event, which occurs before the Page object is eliminated. In this event, you should free up any critical resources (such as files, graphics objects, database connections, and so on) that might be used.

After this event, and finally, the browser receives the HTTP response packet and displays the page.

Summary

The ASP. NET Page object model is exceptionally novel and unique due to its event mechanism. Web pages are composed of controls that produce rich HTML-based user interfaces and can interact with the user through events. Previously, setting up an event model in the context of a WEB application was a challenging task. We are surprised to see that the client-generated events can be resolved by the server-side code, and that the process can still output the same HTML page after only some corresponding modifications.

Mastering this model is important for understanding the various stages of the page life cycle and how page objects are instantiated and used by the HTTP runtime.

Page event (Init,load,prerender) execution order

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.