ASP. Net Web Page

Source: Internet
Author: User

5. Page Lifecycle

Now back to the content mentioned in the third title, we talked about the HttpApplication instance receiving requests and creating page class instances, in fact, this instance is an instance of the dynamically compiled ASPX class. In the previous title, we learned that ASPX is actually a subclass of the class in code binding, so it inherits all the protected methods.

Now let's take a look at the CodeBehind class code automatically generated by VS. Net to start our discussion on the page lifecycle:

# Region Web Form Designer generated code

Override protected void OnInit (EventArgs e)

{

//

// CODEGEN: This call is required by the ASP. NET Web form designer.

//

InitializeComponent ();

Base. OnInit (e );

}

/// <Summary>

/// The designer supports the required methods-do not use the code editor to modify

/// Content of this method.

/// </Summary>

Private void InitializeComponent ()

{

This. Maid + = new System. Web. UI. WebControls. Maid (this. Maid );

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

}

# Endregion

This is to use. net Page code. We can see that there are two methods, one is OnInit and the other is InitializeComponent, and the latter is called by the former. In fact, this is the beginning of Page initialization, in InitializeComponent, we can see the control event Declaration and the Page Load declaration.

The following is a description extracted from MSDN and a sequence table of page lifecycle methods and event triggering:

"Each time an ASP. NET page is requested, the server will load an ASP. NET page and uninstall the page when the request is complete. The page and its server control are responsible for executing the request and rendering the HTML to the client. Although the communication between the client and the server is stateless and intermittent, the customer must feel that this is a continuous execution process ."

"The illusion of continuity is implemented by the ASP. NET page framework, pages, and controls. After sending the API back, the control action must start from the end of the last Web request. Although the ASP. NET page framework makes execution status management easier, control developers must know the execution sequence of controls to achieve continuity. Control developers need to know: in each stage of the control lifecycle, what information can be used by the Control, what data can be maintained, and what status the control is in when presented. For example, the control cannot call its parent level before filling the control tree on the page ."

"The following table provides an advanced overview of each stage of the control lifecycle. For more information, click the link in the table ."

Phase
Operations to be performed by the Control
Method or event to be overwritten

Initialization
Initialize the settings required during the lifecycle of the incoming Web request. See process inherited events.
Init event (OnInit method)

Load view status
The ViewState attribute of the control is automatically filled at the end of this phase. For details, see the description of the status in the maintenance control. Controls can override the default implementation of the LoadViewState method to restore a custom state.
LoadViewState Method

Process the returned data
Process input form data and update properties accordingly. See process sending back data.

Note that only the control that processes the returned data participates in this phase.
LoadPostData Method

(If IPostBackDataHandler has been implemented)

Load
Perform common operations for all requests, such as setting database queries. In this case, the server control in the tree has been created, initialized, and restored, and the Form Control reflects the client data. See process inherited events.
Load event

(OnLoad method)

Send a change notification
A change event is triggered to respond to status changes between the current and previous sending. See process sending back data.

Note that only the control that triggers the send-back change event participates in this phase.
RaisePostDataChangedEvent Method

(If IPostBackDataHandler has been implemented)

Handle sending back events
Process client events that cause sending back, and trigger corresponding events on the server. See capture sending back events.

Note that only the control that handles the send-back event participates in this phase.
RaisePostBackEvent Method

(If IPostBackEventHandler has been implemented)

Pre-rendering
Execute any update before rendering the output. Changes made to the control status during the pre-rendering phase can be saved, while changes made during the rendering phase will be lost. See process inherited events.
PreRender event

(OnPreRender method)

Save status
After this phase, the ViewState attribute of the control is automatically kept in the string object. This string object is sent to the client and sent back as a hidden variable. To improve efficiency, the control can override the SaveViewState method to modify the ViewState attribute. See maintain the status in the control.
SaveViewState Method

Rendering
Generate the output presented to the client. See rendering ASP. NET Server controls.
Render Method

Disposal
Execute all final cleanup operations before the control is destroyed. Reference to expensive resources, such as database links, must be released at this stage. See methods in ASP. NET Server controls.
Dispose Method

Uninstall
Execute all final cleanup operations before the control is destroyed. The control creator usually clears the event in Dispose instead of processing the event.
UnLoad event (On UnLoad method)

From this table, we can clearly see the call method and trigger time of a Page from loading to detaching. Next we will analyze it in depth.

After reading the table above, a careful friend may ask, since OnInit is the beginning of the page lifecycle, we mentioned in the previous section that controls are created in child classes, so here we can actually use the field of the sound name in the parent class in the InitializeComponent method, which means that the initialization of the subclass is more before this?

In the third title, we mentioned that the ProcessRequest of the page class is the beginning of the page declaration cycle in the true sense. This method is called by HttpApplication (the call method is complex, I have the opportunity to write an article separately). A Page is used to process the request through decompilation. net class library to view the source code, we found in the System. web. webControls. base class of Page: System. web. webControls. templateControl (which is the base class of the Page and user control) defines a "FrameworkInitialize" virtual method, and then calls this method in Page ProcessRequest first, we found this method in the source code of ASPX generated by the generator. All controls are initialized in this method, and the Control tree on the page is generated at this time.

The next step is simple. We will analyze every item in the page lifecycle step by step:

1. Initialization

Initialize the Init event and OnInit method of the corresponding Page.

If you want to rewrite it, the recommended method of MSDN is to reload the OnInti method, instead of adding an Init event proxy. The two are different. The former can control the order of calling the parent class OnInit method, the latter can only be executed after the OnInit of the parent class (actually called in OnInit ).

2. Load view status

This is an important method. We know that each request is actually handled by different page-class instances. To ensure the status of the two requests, ASP. net uses ViewState. For more information about ViewState, see my own article:

Http://expert.csdn.net/Expert/topic/1558/1558798.xml? Temp =. 2561609.

The LoadViewState method obtains the last state from the ViewState and uses recursion to traverse the entire tree based on the control tree structure of the page to restore the corresponding state to each control.

3. process the returned data

This method is used to check whether the status of the control data sent back from the client has changed. Method prototype:

Public virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)

PostDataKey is the Key that identifies the control (that is, the Key in postCollection). postCollection is a set of returned data. We can rewrite this method and check whether the returned data has changed, if yes, a True value is returned. "If the control status changes due to sending back, LoadPostData returns true; otherwise, false is returned. The page framework tracks all controls that return true and calls RaisePostDataChangedEvent on these controls ." (From MSDN)

This method is System. web. webControls. the custom Control defined in Control is also the method for processing all custom controls that need to process events. For the Page we are discussing today, you can ignore it.

4. Load

Load the corresponding Load event and OnLoad method. I believe most of my friends will be familiar with this event. the Page_Load method in the page generated by Net is the method for responding to the Load event. For each request, the Load event is triggered and the Page_Load method is executed. I believe most people know about ASP. net.

The Page_Load method responds to the Load event, which is in the System. web. webControl. defined in the Control class (this class is the ancestor of Page and all server controls), and is triggered in the OnLoad method.

Many people may have encountered such a problem. They wrote a PageBase class and then verified the user information in Page_Load. The results showed that Page_Load on the subclass page is always executed no matter whether the verification is successful or not, this may leave some security risks. The user may execute the Page_Load method in the subclass without being verified.

The reason for this problem is very simple, because the Page_Load method is added to the Load event in OnInit, And the OnInit method of the subclass adds the Load event first, and then calls the base. onInit, which causes the Page_Load of the subclass to be added first and then executed first.

There are two ways to solve this problem:

1) Reload the OnLoad method in PageBase, verify the user in OnLoad, and then call base. onLoad, because the Load event is triggered in OnLoad, so that we can ensure that the user is verified before the Load event is triggered.

2) Call base. OnInit in the OnInit method of the subclass to ensure that the parent class executes Page_Load first.

5. Send a change notification

This method corresponds to the process of sending back data in step 1. If the process returns True, the page framework will call this method to trigger the data change event.

Related Article

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.