asp.net page life cycle-msdn__.net

Source: Internet
Author: User
asp.net page life cycle overview

When the ASP.net page runs, this page undergoes a lifecycle and a series of processing steps are performed during the lifecycle. These steps include initializing, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important to understand the page lifecycle, because doing so allows you to write code at the appropriate stage of the lifecycle to achieve the desired results. In addition, if you are developing a custom control, you must familiarize yourself with the page lifecycle so that the control is initialized correctly, the control properties are populated with view state data, and any control behavior code is run. (The life cycle of a control is based on the life cycle of the page, but the page raises more control events than is available in a separate asp.net page.) General page life cycle phase

In general, pages go through the stages outlined in the following table. In addition to the page lifecycle phase, there is an application phase before and after the request, but these phases are not specific to the page. For more information, see ASP.net Application Lifecycle overview.

Stage Description

Page requests

Page requests occur before the page life cycle begins. When a user requests a page, ASP.net determines whether the page needs to be parsed and compiled (thereby starting the life cycle of the page), or whether a cached version of the page can be sent to respond without running the page.

Begin

In the start phase, page properties, such as Request and Response, are set. At this stage, the page also determines whether the request is a postback request or a new request, and sets the IsPostBack property. In addition, the UICulture property of the page is also set during the start phase.

Page initialization

During page initialization, you can use the controls on the page and set the UniqueID property for each control. In addition, any theme will be applied to the page. If the current request is a postback, the postback data has not been loaded, and the control property value has not been restored to the value in view state.

Load

During load, if the current request is a postback request, the control properties are loaded using information recovered from view state and control state.

Verify

During validation, the Validate method for all validator controls is invoked, and this method sets the IsValid properties for each validator control and page.

Postback event handling

If the request is a postback, all event handlers are invoked.

Present

The view state is saved for the page and for all controls before rendering. In the rendering phase, the page invokes the Render method for each control, which provides a text writer that writes the output of the control to the outputstream of the page's Response property.

Unloading

The uninstall is invoked when the page is fully rendered and the page has been sent to the client, and the page is ready to be discarded. The page properties (such as Response and Request) are unloaded and cleanup is performed.

Life Cycle Events

In each phase of the page lifecycle, the page raises events that can run your own code for processing. For control events, you can bind an event handler to an event by using a property declaratively, such as onclick, or in a way that uses code.

The page also supports automatic event connections, that is, ASP.net will look for methods with a specific name and run them automatically when a particular event is raised. If the AutoEventWireup property of the @ Page directive is set to true(or if the property is not defined, because the property defaults to true), the page event is automatically bound to the use of the Page_ The method of naming conventions for events (such as Page_Load and Page_Init). For more information about automatic event connections, see the asp.net Web server control event model.

The following table lists the most commonly used page life cycle events. There are other events in addition to the events listed, but most page-handling scenarios do not use these events. Instead, they are primarily used by server controls on ASP.net Web pages to initialize and render themselves. If you are writing your own ASP.net server control, you need to understand these phases in detail. For information about creating custom controls, see Developing custom ASP.net server controls.

Page Events Typical use

PreInit

Use this event to perform the following actions:

Check the IsPostBack property to determine if the page is being processed for the first time.

Create or recreate a dynamic control.

Dynamically set the master page.

Dynamically set the Theme property.

Reads or sets the profile property value.

Attention

If the request is a postback, the value of the control has not been restored from view state. If you set control properties at this stage, their values may be overridden in the next event.

Init

Raised after all controls have been initialized and all skin settings have been applied. Use this event to read or initialize the properties of a control.

InitComplete

Raised by the Page object. Use this event to handle tasks that require you to complete all initialization work first.

Preload

Use this event if you need to perform processing on the page or control before the Load event.

After the Page raises the event, it loads view state for itself and all controls, and then handles any postback data that is included with the Request instance.

Load

page increases the OnLoad event method on page and then recursively performs the same operation on each child control, so that it repeats until the page and all the controls are loaded.

Use the OnLoad event method to set properties in the control and establish a database connection.

Control events

Use these events to handle specific control events, such as the Click event of a Button control or the TextChanged event of a TextBox control.

Attention

In a postback request, if the page contains a validator control, check the IsValid properties of the page and each validation control before performing any processing.

LoadComplete

Use this event for tasks that need to load all other controls on the page.

PreRender

Before this event occurs:

The Page object invokes ensurechildcontrols for each control and page.

Each data-bound control that has the DataSourceID property set invokes the DataBind method. For more information, see Data-binding events for data-bound controls below.

PreRender events occur for each control on the page. Use this event to make a final change to the contents of a page or its controls.

Savestatecomplete

ViewState was saved for the page and for all controls before the event occurred. Any changes made to the page or control at this time will be ignored.

Use this event to perform a task that requires that view state has been saved, but that no changes have been made to the control.

Render

This is not an event; At this stage of processing, thePage object will be raised with this method on each control. All asp.net Web server controls have a Render method for writing a control tag that is set to be sent to the browser.

If you create a custom control, you typically override this method to output the markup for the control. However, if your custom control merges only standard asp.net Web server controls and does not incorporate custom tags, you do not need to override the Render method. For more information, see Developing custom ASP.net server controls.

The user control (. ascx file) automatically merges the rendering, so you do not need to render the control explicitly in your code.

Unload

This event occurs first for each control, and then for that page. In a control, use this event to perform a final cleanup of a specific control, such as closing a control-specific database connection.

For the page itself, use this event to perform the final cleanup work, such as closing open files and database connections, or completing logging or other request-specific tasks.

Attention

In the uninstall phase, the page and its controls are rendered and cannot be further changed for the response stream. If you try to invoke a method, such as the Response.Write method, the page throws an exception.

additional page life cycle considerations

Each asp.net server control has its own lifecycle that is similar to the page life cycle. For example, the Init and Load events for a control occur during the corresponding page event.

Although both Init and Load occur recursively on each control, they occur in the opposite order. The Init event (and the Unload event) For each child control occurs before the corresponding event is raised for its container (from bottom to top). However, the container's load event occurs before its child control's load event (from top to bottom).

You can customize the appearance or content of a control by handling its events, such as the Button control's Click event and the SelectedIndexChanged event of the ListBox control. In some cases, you may also want to handle the control's DataBinding or DataBound events. For more information, see the class reference topics for individual controls and develop custom ASP.net server controls.

When inheriting a class from the page class, you can override the methods in the base class of the page in addition to the events raised by the pages. For example, you can override the page's InitializeCulture method to dynamically set culture information. Note that when you create an event handler using the Page_ event syntax, the base implementation is called implicitly, so you do not need to call it in the method. For example, the OnLoad method of the page base class is always invoked whether or not the Page_Load method is created. However, if you override the OnLoad method of the page using the override keyword ( Overridesin Visual Basic), you must explicitly call the base method. For example, if you override the OnLoad method in a page, you must call base. Load( mybase.loadin Visual Basic) to run the base implementation. catch events for the added control

If the controls are created dynamically at run time, or are created declaratively in the templates of a data-bound control, their events are initially not synchronized with the events of other controls on the page. For example, for controls added at run time, theInit and Load events may occur much later in the page life cycle than the same events that were created declaratively. Therefore, from the moment of instantiation, the events of the dynamically added control will always occur after the event of the control in the template until the control is joined to the Controls collection.

In general, you don't have to worry about this unless you have nested data-bound controls. If a child control has performed data binding, but its container control has not yet performed data binding, the data in the child control may not be synchronized with the data in its container control. This is especially true if the data in the child control is processed according to the data-bound value in the container control.

For example, suppose there is a GridView, each row of it shows a company record, and there is a ListBox control that contains a list of company managers. To populate the list of managers, you need to bind the ListBox control to a data source control (such as SqlDataSource), which uses CompanyID in the query to retrieve company manager data.

If you set the data-binding properties of the ListBox control declaratively (such as DataSourceID and DataMember), theListBox control will attempt to include the row in the DataBinding Bind to its data source during the event. However, the CompanyID field of the row does not contain a value until the RowDataBound event of the GridView control occurs. In this case, the child controls (theListBox control) are bound first, and then the binding contains the control (theGridView control), so their data-binding phase is not synchronized.

To avoid this situation, you need to place the data source control of the ListBox control with the ListBox control itself in the same template item, and do not declaratively set the data-binding property of the listbox . Instead, you set them programmatically at run time during the RowDataBound event, so that the ListBox control is bound to its data when the CompanyID information is available.

For more information, see Binding to data using data source controls. Data -bound events for data-bound controls

To help you understand the relationship between page lifecycles and data-bound events, the following table lists data-related events in data-bound controls such as GridView, DetailsView, and FormView controls.

Control Events Typical use

DataBinding

This event is raised by a data-bound control before the PreRender event that contains the control (or Page object), marking the starting point of the binding process for the control to the data.

Use this event to manually open the database connection, if necessary. (data source controls typically do not need to be done this way.) )

RowCreated ( GridViewonly) or itemcreated (DataList,DetailsView, SiteMapPath, DataGrid, FormView and Repeater controls)

Use this event to manipulate content that is not dependent on data binding. For example, at run time, you can programmatically add formatting to a header or footer row in a GridView control.

rowdatabound( GridViewonly) or ItemDataBound (DataList,SiteMapPath,DataGrid and Repeater controls)

When the event occurs, the data in the row or item is available, so you can format the data on the child data source control or set the FilterExpression property to display the related data in the row or item.

databound

This event marks the end of a data-binding operation in a data-bound control. In the GridView control, data binding is completed for all rows and any child controls.

Use this event to format data-bound content, or to start data binding in other controls that rely on values from the current control's content. (For more information, see "catch-up events for added controls" earlier in this topic.) )

Login Control Events

The Login control can use the settings in the Web.config file to automatically manage membership validation. However, if your application requires you to customize how the control works, or if you want to understand how the Login control event relates to the page lifecycle, you can use the events that are listed in the following table.

Control Events Typical use

Loggingin

During a postback, the event is raised when the page's loadcomplete event occurs. It marks the starting point of the logon process.

Use this event for tasks that must occur before the validation process begins.

Authenticate

The event is raised after the loggingin event.

Use this event to override or enhance the default validation behavior of the Login control.

LoggedIn

This event is raised after the user name and password are validated.

Use this event to redirect to another page or to dynamically set the text in the control. If an error occurs or the validation fails, the event does not occur.

Loginerror

If the validation fails, the event is raised.

Use this event to set the problem interpretation text in the control or to direct the user to a different page.

Please see ReferenceValidating user input in the ASP.net web page
asp.net Login Control Overview
Conceptasp.net Web server control event model
asp.net page and application contexts in a WEB application
View State Overview
To bind to data by using a data source control
Other ResourcesDeveloping custom ASP.net server controls
asp.net page syntax
Server event handling in asp.net Web pages
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.