Sunteți pe pagina 1din 11

ASP.

NET PAGE LIFE CYCLE OVERVIEW


When an ASP.NET page runs, the page goes through a life cycle in which it
performs a series of processing steps. These include initialization,
instantiating controls, restoring and maintaining state, running event
handler code, and rendering. It is important for you to understand the page
life cycle so that you can write code at the appropriate life-cycle stage for
the effect you intend.

General Page Life-cycle Stages


In general terms, the page goes through the stages outlined in the following
table. In addition to the page life-cycle stages, there are application stages
that occur before and after a request but are not specific to a page. For
more information, see ASP.NET Application Life Cycle Overview for IIS 7.0.

Stage

Description

Page request

The page request occurs before the page life cycle begins. When the page
is requested by a user, ASP.NET determines whether the page needs to be
parsed and compiled (therefore beginning the life of a page), or whether a
cached version of the page can be sent in response without running the
page.

Start

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

Page
initialization

During page initialization, controls on the page are available and each
control's UniqueID property is set. Any themes are also applied to the
page. If the current request is a postback, the postback data has not yet
been loaded and control property values have not been restored to the
values from view state.

Load

During load, if the current request is a postback, control properties are


loaded with information recovered from view state and control state.

Validation

During validation, the Validate method of all validator controls is called,


which sets the IsValid property of individual validator controls and of the
page.

Postback
event
handling

If the request is a postback, any event handlers are called.

Rendering

Before rendering, view state is saved for the page and all controls. During
the rendering phase, the page calls the Render method for each control,
providing a text writer that writes its output to the OutputStream of the
page's Responseproperty.

Unload

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.

Life-cycle Events
Within each stage of the life cycle of a page, the page raises events that you
can handle to run your own code. For control events, you bind the event
handler to the event, either declaratively using attributes such as onclick,
or in code.
Pages also support automatic event wire-up, meaning that ASP.NET looks for
methods with particular names and automatically runs those methods when
certain events are raised. If the AutoEventWireup attribute of
the @ Page directive is set to true (or if it is not defined, since by default it
is true), page events are automatically bound to methods that use the
naming convention of Page_event, such as Page_Load and Page_Init. For
more information on automatic event wire-up, see ASP.NET Web Server
Control Event Model.
The following table lists the page life-cycle events that you will use most
frequently. There are more events than those listed; however, they are not
used for most page processing scenarios. Instead, they are primarily used
by server controls on the ASP.NET Web page to initialize and render
themselves. If you want to write your own ASP.NET server controls, you
need to understand more about these stages. For information about creating
custom controls, see Developing Custom ASP.NET Server Controls.

Page Event

Typical Use

PreInit

Use this event for the following:


Check the IsPostBack property to determine
whether this is the first time the page is being
processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
Note:
If the request is a postback, the values of the
controls have not yet been restored from view
state. If you set a control property at this stage, its
value might be overwritten in the next event.

Init

Raised after all controls have been initialized and any


skin settings have been applied. Use this event to read
or initialize control properties.

InitComplete

Raised by the Page object. Use this event for


processing tasks that require all initialization be
complete.

PreLoad

Use this event if you need to perform processing on


your page or control before the Load event.
Before the Page instance raises this event, it loads
view state for itself and all controls, and then
processes any postback data included with
the Request instance.

Load

The 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.
Use the OnLoad event method to set properties in
controls and establish database connections.

Control events

Use these events to handle specific control events,

such as a Button control's Click event or


a TextBox control's TextChangedevent.
Note:
In a postback request, if the page contains validator
controls, check the IsValid property of the Page and of
individual validation controls before performing any
processing.
LoadComplete

Use this event for tasks that require that all other
controls on the page be loaded.

PreRender

Before this event occurs:


The Page object calls EnsureChildControls for each
control and for the page.
Each data bound control
whose DataSourceID property is set calls
its DataBind method. For more information,
seeData Binding Events for Data-Bound
Controls later in this topic.
The PreRender event occurs for each control on the
page. Use the event to make final changes to the
contents of the page or its controls.

SaveStateComplete Before this event occurs, ViewState has been saved for
the page and for all controls. Any changes to the page
or controls at this point will be ignored.
Use this event perform tasks that require view state to
be saved, but that do not make any changes to
controls.
Render

This is not an event; instead, at this stage of


processing, the Page object calls this method on each
control. All ASP.NET Web server controls have
a Render method that writes out the control's markup
that is sent to the browser.
If you create a custom control, you typically override
this method to output the control's markup. However,
if your custom control incorporates only standard
ASP.NET Web server controls and no custom markup,
you do not need to override the Render method. For
more information, see Developing Custom ASP.NET
Server Controls.
A user control (an .ascx file) automatically

incorporates rendering, so you do not need to


explicitly render the control in code.
Unload

This event occurs for each control and then for the
page. In controls, use this event to do final cleanup for
specific controls, such as closing control-specific
database connections.
For the page itself, use this event to do final cleanup
work, such as closing open files and database
connections, or finishing up logging or other requestspecific tasks.
Note:
During the unload stage, the page and its controls
have been rendered, so you cannot make further
changes to the response stream. If you attempt to call
a method such as the Response.Write method, the
page will throw an exception.

ASP.NET Web Server Control Event Model


An important feature of ASP.NET is that it allows you to program Web pages using
an event-based model that is similar to that in client applications. As a simple
example, you can add a button to an ASP.NET Web page and then write an event
handler for the button's click event. Although this is common in Web pages that
work exclusively with client script (by handling the button's onclick event in
dynamic HTML), ASP.NET brings this model to server-based processing.
Events raised by ASP.NET server controls work somewhat differently than events in
traditional HTML pages or in client-based Web applications. The difference arises
primarily because of the separation of the event itself from where the event is
handled. In client-based applications, events are raised and handled on the client.
In ASP.NET Web pages, however, events associated with server controls originate
on the client (browser) but are handled on the Web server by the ASP.NET page.
For events raised on the client, the ASP.NET Web control event model requires that
the event information be captured on the client and an event message transmitted
to the server, through an HTTP post. The page must interpret the post to determine
what event occurred and then call the appropriate method in your code on the
server to handle the event.

ASP.NET handles the task of capturing, transmitting, and interpreting the event.
When you create event handlers in an ASP.NET Web page, you can typically do so
without thinking about how the event information is captured and made available to
your code. Instead, you can create event handlers in much the same way you
would in a traditional client form. However, there are some aspects of event
handling in ASP.NET Web pages that you should be aware of.

Event Set for Server Controls and Pages


Because most ASP.NET server control events require a round trip to the server for
processing, they can affect the performance of a page. Therefore, server controls
offer a limited set of events, usually only click-type events. Some server controls
support change events. For example, the CheckBox Web server control raises
a CheckedChanged event in server code when the user clicks the box. Some server
controls support more abstract events. For example, theCalendar Web server
control raises a SelectionChanged event that is a more abstract version of a click
event.
Events that occur often (and can be raised without the user knowing it), such as
an onmouseover event, are not supported for server controls. ASP.NET server
controls can still call client-side handlers for those events, as explained later
under ASP.NET Web Server Control Event Model.
Controls and the page itself also raise life-cycle events at each processing step,
such as Init, Load, and PreRender. You can take advantage of these life-cycle
events in your application. For example, in a page's Load event, you can set
default values for controls.

Event Arguments
Server-based ASP.NET page and control events follow a standard .NET Framework
pattern for event-handler methods. All events pass two arguments: an object
representing the object that raised the event, and an event object containing any
event-specific information. The second argument is usually of type EventArgs, but
for some controls is of a type specific to that control. For example, for
an ImageButton Web server control, the second argument is of
typeImageClickEventArgs, which includes information about the coordinates where
the user has clicked.
Note:

Events for the page (for example, the page's Load event) can accept the standard two argument
passed in these arguments.

Postback and Non-Postback Events in Server Controls


In server controls, certain events, typically click events, cause the page to be
posted back immediately to the server. Change events in HTML server controls and
Web server controls, such as the TextBox control, do not immediately cause a post.
Instead, they are raised the next time a post occurs.

Note:

If the browser supports it, validation controls can check user input using client script, without a r
server. For details, see Validating User Input in ASP.NET Web Pages.
After a page has been posted back, the page's initialization events
(Page_Init and Page_Load) are raised, and then control events are processed.
You should not create application logic that relies on the change events being raised
in a specific order unless you have detailed knowledge of page event processing.
For details, see ASP.NET Page Life Cycle Overview.
If it useful for your application, you can specify that change events cause the page
to post. Web server controls that support a change event include
anAutoPostBack property. When this property is true, the control's change event
causes the page to post immediately, without waiting for a click event. For
example, by default, a CheckBox control's CheckedChanged event does not cause
the page to be submitted. However, if you set the control's AutoPostBackproperty
to true, as soon as a user clicks the check box, the page is sent to the server for
processing.
Note:

For the AutoPostBack property to work properly, the user's browser must be set to allow script
default in most cases. However, some users disable scripting for security reasons. For details, se
ASP.NET Web Pages.

Forwarded Events
Web server controls such as the Repeater, DataList, GridView, FormView,
and DetailsView controls can contain button controls that themselves raise events.
For example, each row in a GridView control can contain one or more buttons
created dynamically by templates.
Rather than each button raising an event individually, events from the nested
controls are forwarded to the container control. The container in turn raises a
generic ItemCommand event with parameters that allow you to discover which
individual control raised the original event. By responding to this single event, you
can avoid having to write individual event handlers for child controls.
The ItemCommand event includes the two standard event arguments, an object
referencing the source of the event and an event object containing event-specific
information.
Note:

The GridView, DataList, and other data controls support additional events, such
as EditCommand, DeleteCommand, and UpdateCommand, that are special cases of forward
With buttons, you can use the CommandArgument property to pass a userspecified string to the event handler to help you identify what button raised the

event. For example, in a DataList control, buttons raise the ItemCommand event.
You can set the CommandArgument property of each button to a different
valueperhaps one button's value is "ShowDetails" and another button's value is
"AddToShoppingCart"and then capture those values in the event handler later.

Binding Events to Methods


An event is a message like "a button has been clicked". In your application, the
message must be translated into a method call in your code. The binding between
the event message and a specific methodthat is, an event handleris done using
an event delegate. For more information, see Events and Delegates.
In ASP.NET Web pages, you do not need to explicitly code delegates if the control is
created declaratively (in markup) on the page. Event binding can be accomplished
in various ways, depending on what event you are binding and what programming
language you are using. For details, see How to: Create Event Handlers in ASP.NET
Web Pages.
Binding Control Events
For controls declared on the page, you can bind an event to a method by setting an
attribute (property) in the control's markup. The following code example shows how
to bind the Click event of an ASP.NET Button control to a method
named ButtonClick.

<asp:button id="SampleButton" runat="server"


text="Submit" onclick="ButtonClick" />
When the page is compiled, ASP.NET looks for a method named ButtonClick and
confirms that the method has the appropriate signature (it accepts two arguments,
one of type Object and another of type EventArgs). ASP.NET then automatically
binds the event to the method.
In Visual Basic, you can alternatively bind events to methods using
the Handles keyword in the event handler declaration, as in the following code
example:
Visual Basic

Private Sub ButtonClick(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles SampleButton.Click
Binding Page Events
ASP.NET pages raise life-cycle events such as Init, Load, PreRender, and others.
By default, you can bind page events to methods using a naming convention
of Page_eventname. For example, to create a handler for the page's Load event,
you can create a method named Page_Load. At run time, ASP.NET will find
methods based on this naming convention and automatically perform the binding
between the event and the method. You can use the convention
ofPage_eventname for any event exposed by the Page class.

Note:
Page event-handling methods do not require any arguments.
If you prefer, you can bind handlers to events explicitly. The automatic binding of
page events based on the method naming convention is controlled by a page
property named AutoEventWireup. By default, for C#, this property is set
to true, and ASP.NET performs the automatic lookup and binding described earlier.
Alternatively, you can set this property to false by adding the
attribute AutoEventWireup=false in the @ Page directive. You can then create
methods with any name and bind them to page events explicitly.
By default, for Visual Basic, this property is set to false. In Visual Basic, handlers
are bound to events by using the Handles keyword. This keyword is inserted
automatically by Visual Studio as part of the method that you create when you
select a page event from the drop-down box. The following example illustrates use
of the Handles keyword:
Visual Basic

Sub MyPageLoad(sender As Object, e As EventArgs) Handles


MyBase.Load
One disadvantage of the AutoEventWireup attribute is that it requires that the
page event handlers have specific, predictable names. This limits your flexibility in
how you name event handlers. Another disadvantage is that performance is
adversely affected, because ASP.NET searches for methods at run-time. For a Web
site with high traffic volumes, the impact on performance could be significant.
Note:

If you include explicit binding for page events, be sure that the AutoEventWireup property is se
the method is not called twice.
Explicit Binding for Dynamic Controls
If you create controls by declaring them in markup, you can bind events to
methods using an attribute (for example, onclick) or in Visual Basic, by using
theHandles keyword. If you create controls dynamically (in code), you cannot use
either of these methods, because the compiler does not have a reference to the
control at compilation time.
In that case, you must use explicit event binding. In Visual Basic, you can use
the AddHandler statement to bind an event in a dynamically created control to an
existing method. In C#, you create a delegate and associate it with the control's
event. The following code example shows how you can bind a method
namedButtonClick to a button's Click event:
Visual Basic

Dim b As New Button

b.Text = "Click"
AddHandler b.Click, AddressOf ButtonClick
Placeholder1.Controls.Add(b)
C#

Button b = new Button;


b.Text = "Click";
b.Click += new System.EventHandler(ButtonClick);
Placeholder1.Controls.Add(b);

Responding to Both Client and Server Events in ASP.NET


Server Controls
This topic has discussed how to work with events raised in server code. Controls
render elements to the browser, and those elements can also raise client-side
events that you can handle in client script. Using client script, you can add mouse
and keyboard event handling to ASP.NET server controls. For more information,
see Client Script in ASP.NET Web Pages and How to: Add Client Script Events to
ASP.NET Web Server Controls.

Application and Session Events


In addition to page and control events, ASP.NET provides ways for you to work with
life-cycle events that are raised when your application starts or stops or when an
individual user's session starts or stops, including the following:

Application events are raised for all requests to an application. For example,
the BeginRequest event of the HttpApplication object
(Application_BeginRequest) is raised when any ASP.NET Web page or
XML Web service in your application is requested. This event allows you to
initialize resources that will be used for each request to the application. A
corresponding event, the EndRequest event of the HttpApplication object
(Application_EndRequest), provides you with an opportunity to close or
otherwise dispose of resources used for the request.

Session events are similar to application events (there is a Start and


an End event), but are raised with each unique session within the application.
A session begins when a user requests a page for the first time from your
application and ends either when your application explicitly closes the session
or when the session times out.

S-ar putea să vă placă și