Dotnetfreaks' Blog | ASP.NET 4.0

Dotnetfreaks' Blog

Fabulous Adventures In DotNet

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Archive

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Ajax Client Life-Cycle Events


A WebForms based page that uses Microsoft Ajax raises the same server life-cycle events as an ASP.NET 4 Web page and in addition raises client life-cycle events. The client events enable you to customize the UI for both postbacks and for asynchronous postbacks (partial-page updates). The client events also help you manage custom script components during the lifetime of the page in the browser.

The client events are raised by classes in the Microsoft Ajax Library. These classes are automatically instantiated when a page contains Microsoft Ajax server controls. The client classes provide APIs that enable you to bind to events and to provide handlers for those events. Because the Microsoft Ajax Library is browser independent, the code you write for your handlers works the same in all supported browsers.

The key event for initial requests (GET requests) and synchronous postbacks is the load event of the Application instance. When script in a load event handler runs, all scripts and components have been loaded and are available. When partial-page rendering with UpdatePanel controls is enabled, the key client events are the events of the PageRequestManager class. These events enable you to handle many common scenarios. These include the ability to cancel postbacks, to give precedence to one postback over another, and to animate UpdatePanel controls when their content is refreshed.

Client events are useful whether you are creating pages or writing components. If you are a page developer, you can provide custom script that is called when the page loads and unloads in the browser.

For more information about the server life-cycle events, see ASP.NET Page Life Cycle Overview.

Client Classes


The two main Microsoft Ajax Library classes that raise events during the client life cycle of a WebForms based page are the Application and PageRequestManager classes.

The Application class is instantiated in the browser when the page contains a ScriptManager control. The Application class resembles the Page server control, which derives from the Control class, but provides additional functionality for raising server events. Similarly, the Application class derives from the Sys.Component class, but raises client life-cycle events that you can handle.

If a page contains a ScriptManager control and one or more UpdatePanel controls, the page can perform partial-page updates (if partial-page rendering is enabled and supported in the browser). In that case, an instance of the PageRequestManager class is automatically available in the browser. The PageRequestManager class raises client events that are specific to asynchronous postbacks. For details about partial-page rendering, see Partial-Page Rendering Overview.

Adding Handlers for Client Events


To add or remove handlers for events raised by the Application and PageRequestManager classes, use the add_eventname and remove_eventname methods of those classes. The following example shows how to add a handler named MyLoad to the init event of the Application object.

JavaScript

Sys.Application.add_init(MyInit);
                function MyInit(sender) {
                }
                Sys.Appplication.remove_init(MyInit);
                

Handling the Application Load and Unload Events

To handle the load and unload events of the Application object, you do not have to explicitly bind a handler to the event. Instead, you can create functions that use the reserved names pageLoad and pageUnload. The following example shows how to add a handler for the load event of the Application object by using this approach.

JavaScript

function pageLoad(sender, args) {
                }
            

Events for Other Client Classes

This topic describes only the events that are raised by the Application and PageRequestManager classes. The Microsoft Ajax Library also contains classes for adding, clearing, and removing handlers for DOM element events. These classes include the following:

Events raised by DOM elements are not discussed in this topic.

Client Events of the Application and PageRequestManager Classes


The following table lists client events of the Application and PageRequestManager classes that you can handle in Ajax enabled ASP.NET Web pages. The order in which the events are raised is described later in this topic.

Event

Description

Sys.Application.init Event

Raised after all scripts have been loaded but before any objects are created. If you are writing a component, the init event gives you a point in the life cycle to add your component to the page. The component can then be used by other components or by script later in the page life cycle. If you are a page developer, you should use the load event instead of the init event for most scenarios.

The init event is raised only one time when the page is first rendered. Subsequent partial-page updates do not raise the init event.

Sys.Application.load Event

Raised after all scripts have been loaded and all objects in the application that are created by using $create are initialized. The load event is raised for all postbacks to the server, which includes asynchronous postbacks.

If you are a page developer, you can create a function that has the name pageLoad, which automatically provides a handler for the load event. The pageLoad handler is called after any handlers that have been added to the load event by the add_load method.

The load event takes an eventargs parameter, which is an Sys.ApplicationLoadEventArgs object. You can use the event arguments to determine whether the page is being refreshed as a result of a partial-page update and what components were created since the previous load event was raised.

Sys.Application.unload Event

Raised before all objects are disposed and before the browser window's window.unload event occurs.

If you are a page developer, you can create a function that has the name pageUnload, which automatically provides a handler for the unload event. The pageUnload event is called just before the page is unloaded from the browser. During this event, you should free any resources that your code is holding.

Sys.Component.propertyChanged Event

Potentially raised when a property of a component changes. This event is raised only if a component developer has called the Sys.Component.raisePropertyChange method in a property set accessor. For more information, see Defining Custom Component Properties and Raising PropertyChanged Events.

The propertyChanged event takes an eventargs parameter, which is a Sys.applicationLoadEventArgs object.

Sys.Component.disposing Event

Raised when the Application instance is disposed.

Sys.WebForms.PageRequestManager initializeRequest Event

Raised before an asynchronous request starts. You can use this event to cancel a postback, such as to give precedence to another asynchronous postback.

The initializeRequest event takes an eventargs parameter, which is a Sys.WebForms.InitializeRequestEventArgs object. This object makes available the element that caused the postback and the underlying request object. InitializeRequestEventArgs also exposes a cancel property. If you set cancel to true, the new postback is canceled.

Sys.WebForms.PageRequestManager beginRequest Event

Raised before an asynchronous postback starts and the postback is sent to the server. If there is a postback already processing, it is stopped (by using the abortPostBack method). You can use this event to set request headers or to begin an animation on the page to indicate that the request is in process.

The beginRequest event takes an eventargs parameter, which is a Sys.WebForms.BeginRequestEventArgs object. This object makes available the element that caused the postback and the underlying request object.

Sys.WebForms.PageRequestManager pageLoading Event

Raised after the response from the server to an asynchronous postback is received, but before any content on the page is updated. You can use this event to provide a custom transition effect for updated content.

The pageLoading event takes an eventargs parameter, which is an Sys.WebForms.PageLoadingEventArgs object. This object makes available information about what panels will be deleted and updated as a result of the most recent asynchronous postback.

Sys.WebForms.PageRequestManager pageLoaded Event

Raised after all content on the page is refreshed, as a result of either a synchronous or an asynchronous postback. For synchronous postbacks, panels can only be created, but for asynchronous postbacks, panels can be both created and updated. You can use this event to manage a custom transition effect for updated content.

The pageLoaded event takes an eventargs parameter, which is an Sys.WebForms.PageLoadedEventArgs object. This object makes available information about which panels were updated and created in the most recent postback.

Sys.WebForms.PageRequestManager endRequest Event

Raised after the response for an asynchronous postback is processed and the page is updated, or during the processing of the response if there is an error. If an error occurs, the page is not updated. Use this event to provide customized error notification to users or to log errors.

The endRequest event takes an eventargs parameter, which is a Sys.WebForms.EndRequestEventArgs object. This object makes available information about errors that have occurred and whether the error was handled. It also makes available the response object.

Event Order for Common Scenarios


The order of events depends on what controls are used on the page and what type of request is made (initial request, postback, or asynchronous postback). This section describes the order of events for several common scenarios.

Initial Request

During the initial request for the page, a limited number of client events are raised. Assume the following scenario for the initial request:

The following client events occur, in this order:

  1. The initial request is sent to the server.

  2. The response is received by the client.

  3. The Application instance raises the init event.

  4. The Application instance raises the load event.

The init event of the Application instance is raised only one time for the life of the page in the browser. It is not raised for subsequent asynchronous postbacks. During an initial request, no PageRequestManager events are raised.

Asynchronous Postback

An asynchronous postback sends some page data to the server, receives a response, and updates a part of the page. Assume the following scenario for an asynchronous postback:

The following client events occur, in this order:

  1. The button inside the UpdatePanel is clicked, which initiates an asynchronous postback.

  2. The PageRequestManager instance raises the initializeRequest event.

  3. The PageRequestManager instance raises the beginRequest event.

  4. The request is sent to the server.

  5. The response is received by the client.

  6. The PageRequestManager instance raises the pageLoading event.

  7. The PageRequestManager instance raises the pageLoaded event.

  8. The Application instance raises the load event.

  9. The PageRequestManager instance raises the endRequest event.

For more information, see Working with Partial-Page Rendering Events.

Note that the load event of the Application instance is raised after the PageRequestManager pageLoaded event and before its endRequest event.

Multiple Asynchronous Postbacks

Multiple asynchronous postbacks can occur when users initiate a new request before a previously initiated request has finished processing on the server or in the browser. Assume the following scenario for multiple asynchronous postbacks:

  • The page contains a ScriptManager control and the control's SupportsPartialRendering and EnablePartialRendering property are both true.

  • The page contains an UpdatePanel control.

  • A button inside the UpdatePanel control that initiates an asynchronous postback is clicked two times. The second click occurs while the server is processing the request initiated by the first click.

  • A response to the first request is returned successfully from the server.

The following client events occur, in this order:

  1. A button inside the UpdatePanel is clicked, which initiates an asynchronous postback.

  2. The PageRequestManager instance raises the initializeRequest event.

  3. The PageRequestManager instance raises the beginRequest event.

  4. The request is sent to the server.

  5. The button is clicked again, which initiates a second asynchronous postback.

  6. The PageRequestManager instance raises the initializeRequest event for the second button click.

  7. The PageRequestManager instance raises the endRequest event for the first button click.

  8. The PageRequestManager instance raises the beginRequest event for the second button click.

  9. The request initiated by the second click is sent to the server.

  10. The response is received for the second click.

  11. The PageRequestManager instance raises the pageLoading event.

  12. The PageRequestManager instance raises the pageLoaded event.

  13. The Application instance raises the load event.

  14. The PageRequestManager instance raises the endRequest event.

The default behavior of asynchronous postbacks is that the most recent asynchronous postback takes precedence. If two asynchronous postbacks occur in sequence, and if the first postback is still being processed in the browser, the first postback is canceled. If the first postback has been sent to the server, the server processes the second request when it arrives and does not return the first request. For information about how to give precedence to a specific asynchronous postback, see Giving Precedence to a Specific Asynchronous Postback.

Browsing Away from a Page

When the user browses away from a page, the current page is unloaded from the browser and you can handle the unload event to free resources. Assume the following scenario for browsing away from a page:

The following client events are raised, in this order:

  1. The request for new page is initiated.

  2. The response for the new page is received by the browser.

  3. The Application instance raises the unload event.

  4. The new page is displayed.

If there is an error in the request for the new page, the unload event is still raised, but the new page is not displayed.

MSAJaxEvents.pdf (101.83 kb)




Posted by Ajander Singh on Wednesday, June 29, 2011 6:43 PM
Permalink | Comments (0) | Post RSSRSS comment feed

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.

If you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run control behavior code. The life cycle of a control is based on the page life cycle, and the page raises many of the events that you need to handle in a custom control.

This topic contains the following sections:

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 Introduction to the ASP.NET Application Life Cycle and ASP.NET Application Life Cycle Overview for IIS 7.0.

Some parts of the life cycle occur only when a page is processed as a postback. For postbacks, the page life cycle is the same during a partial-page postback (as when you use an UpdatePanel control) as it is during a full-page postback.

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 stage, 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. The page also sets the UICulture property.

Initialization

During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. 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.

Postback event handling

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Rendering

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

Unload

The Unload event is raised 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 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, 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 custom ASP.NET server controls, you need to understand more about these events. For information about creating custom controls, see Developing Custom ASP.NET Server Controls.

Page Event

Typical Use

PreInit

Raised after the start stage is complete and before the initialization stage begins.

Use this event for the following:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.

  • Create or re-create dynamic controls.

  • Set a master page dynamically.

  • Set the Theme property dynamically.

  • Read or set profile property values.

    NoteNote
    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. The Init event of individual controls occurs before the Init event of the page.

Use this event to read or initialize control properties.

InitComplete

Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.

Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad

Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load

The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.

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

NoteNote
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

Raised at the end of the event-handling stage.

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

PreRender

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete

Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.

SaveStateComplete

Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

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 to send 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

Raised 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 request-specific tasks.

NoteNote
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.

Additional Page Life Cycle Considerations


 

Individual ASP.NET server controls have their own life cycle that is similar to the page life cycle. For example, a control's Init and Load events occur during the corresponding page events.

Although both Init and Load recursively occur on each control, they happen in reverse order. The Init event (and also the Unload event) for each child control occur before the corresponding event is raised for its container (bottom-up). However the Load event for a container occurs before the Load events for its child controls (top-down). Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events.

When you create a class that inherits from the Page class, in addition to handling events raised by the page, you can override methods from the page's base class. For example, you can override the page's InitializeCulture method to dynamically set culture information. Note that when an event handler is created using the Page_event syntax, the base implementation is implicitly called and therefore you do not need to call it in your method. For example, the base page class's OnLoad method is always called, whether you create a Page_Load method or not. However, if you override the page OnLoad method with the override keyword (Overrides in Visual Basic), you must explicitly call the base method. For example, if you override the OnLoad method on the page, you must call base.Load (MyBase.Load in Visual Basic) in order for the base implementation to be run.

The following illustration shows some of the most important methods of the Page class that you can override in order to add code that executes at specific points in the page life cycle. (For a complete list of page methods and events, see the Page class.) The illustration also shows how these methods relate to page events and to control events. The sequence of methods and events in the illustration is from top to bottom, and within each row from left to right.

ASP.NET Page Life Cycle Diagram

Catch-Up Events for Added Controls


 

If controls are created dynamically at run time or declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively. Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.

Data Binding Events for Data-Bound Controls


 

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

Control Event

Typical Use

DataBinding

Raised after the control's PreRender event, which occurs after the page's PreRender event. (This applies to controls whose DataSourceID property is set declaratively. Otherwise the event happens when you call the control's DataBind method.)

This event marks the beginning of the process that binds the control to the data. Use this event to manually open database connections, if required, and to set parameter values dynamically before a query is run.

RowCreated (GridView only) or ItemCreated (DataList, DetailsView, SiteMapPath, DataGrid, FormView, Repeater, and ListView controls)

Raised after the control's DataBinding event.

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

RowDataBound (GridView only) or ItemDataBound (DataList, SiteMapPath, DataGrid, Repeater, and ListView controls)

Raised after the control's RowCreated or ItemCreated event.

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

DataBound

Raised at the end of data-binding operations in a data-bound control. In a GridView control, data binding is complete for all rows and any child controls.

Use this event to format data-bound content or to initiate data binding in other controls that depend on values from the current control's content. (For more information, see Catch-Up Events for Added Controls earlier in this topic.)

Nested Data-Bound Controls

If a child control has been data bound, but its container control has not yet been data bound, the data in the child control and the data in its container control can be out of sync. This is true particularly if the data in the child control performs processing based on a data-bound value in the container control.

For example, suppose you have a GridView control that displays a company record in each row, and it displays a list of the company officers in a ListBox control. To fill the list of officers, you would bind the ListBox control to a data source control (such as SqlDataSource) that retrieves the company officer data using the company ID in a query.

If the ListBox control's data-binding properties, such as DataSourceID and DataMember, are set declaratively, the ListBox control will try to bind to its data source during the containing row's DataBinding event. However, the CompanyID field of the row does not contain a value until the GridView control's RowDataBound event occurs. In this case, the child control (the ListBox control) is bound before the containing control (the GridView control) is bound, so their data-binding stages are out of sync.

To avoid this condition, put the data source control for the ListBox control in the same template item as the ListBox control itself, and do not set the data binding properties of the ListBox declaratively. Instead, set them programmatically at run time during the RowDataBound event, so that the ListBox control does not bind to its data until the CompanyID information is available.

For more information, see Binding to Data Using a Data Source Control.

Login Control Events


 

The Login control can use settings in the Web.config file to manage membership authentication automatically. However, if your application requires you to customize how the control works, or if you want to understand how Login control events relate to the page life cycle, you can use the events listed in the followinbg table.

Control Event

Typical Use

LoggingIn

Raised during a postback, after the page's LoadComplete event has occurred. This event marks the beginning of the login process.

Use this event for tasks that must occur prior to beginning the authentication process.

Authenticate

Raised after the LoggingIn event.

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

LoggedIn

Raised after the user name and password have been authenticated.

Use this event to redirect to another page or to dynamically set the text in the control. This event does not occur if there is an error or if authentication fails.

LoginError

Raised if authentication was not successful.

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




Posted by Ajander Singh on Sunday, May 29, 2011 7:38 PM
Permalink | Comments (0) | Post RSSRSS comment feed