You are on page 1of 21

ASP.

NET AJAX - Introduction

• ASP.NET AJAX, previously called "Atlas", is a Microsoft implementation of


an AJAX based framework, created for ASP.NET (although it can be used on
other platforms as well).
• AJAX stands for Asynchronous JavaScript and XML, which, very simply put,
is a way of transferring data between the server and client without the sending the
entire page, and thereby creating a complete postback. This allows for a richer
experience for the user, since loading dynamic content can be done in the
background, without refreshing and redrawing the entire page. If you have ever
used Gmail or Outlook Web Access, you have used an Ajax enabled web
application, and especially Google have made Ajax very popular.
• AJAX features in ASP.NET enable you to build rich Web applications that have
many advantages over Web applications that are completely server-based. AJAX-
enabled applications offer:
 Improved efficiency, because significant parts of a Web page's processing
are performed in the browser.
 Familiar UI elements such as progress indicators, tooltips, and pop-up
windows.
 Partial-page updates that refresh only the parts of the Web page that have
changed.
 Client integration with ASP.NET application services for forms
authentication, roles, and user profiles.
 Auto-generated proxy classes that simplify calling Web service methods
from client script.
 A framework that lets you customize of server controls to include client
capabilities.
 Support for the most popular and generally used browsers, which includes
Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari.

Architecture of AJAX Features in ASP.NET

The architecture of AJAX features in ASP.NET consists of two pieces:


client-script libraries and server components. These pieces are integrated to provide a
robust development framework.
ASP.NET AJAX client and server architecture

AJAX Client Architecture


The client architecture includes libraries for component support, browser compatibility,
networking, and core services.

Components
• Client components enable rich behaviors in the browser without postbacks.
Components fall into three categories:
- Components, which are non-visual objects that encapsulate code, such as a
timer object.
- Behaviors, which extend the basic behavior of existing DOM elements.
- Controls, which represent a new DOM element that has custom behavior.
• The type of component that you use depends on the type of client behavior you
want. For example, a watermark for an existing text box can be created by using a
behavior that is attached to the text box.

Browser Compatibility
• The browser compatibility layer provides AJAX scripting compatibility for the
most frequently used browsers (including Microsoft Internet Explorer, Mozilla
Firefox, and Apple Safari). This enables you to write the same script regardless of
which supported browser you are targeting.
Networking
• The networking layer handles communication between script in the browser and
Web-based services and applications. It also manages asynchronous remote
method calls. In many common scenarios, such as partial-page updates that use
the UpdatePanel
• The networking layer also provides support for accessing server-based forms
authentication, role information, and profile information in client script. This
support is also available to Web applications that are not created by using
ASP.NET, as long as the application has access to the Microsoft AJAX Library.

Core Services
• The AJAX client-script libraries in ASP.NET consist of JavaScript (.js) files that
provide features for object-oriented development. The object-oriented features
included in the ASP.NET AJAX client-script libraries enable a high level of
consistency and modularity in client scripting. The following core services are
part of the client architecture:
• Object-oriented extensions to JavaScript, such as classes, namespaces, event
handling, inheritance, data types, and object serialization.
• A base class library, which includes components such as string builders and
extended error handling.
• Support for JavaScript libraries that are either embedded in an assembly or are
provided as standalone JavaScript (.js) files. Embedding JavaScript libraries in an
assembly can make it easier to deploy applications and can help solve versioning
issues.

Debugging and Error Handling


• The core services include the Sys.Debug class, which provides methods for
displaying objects in readable form at the end of a Web page. The class also
shows trace messages, enables you to use assertions, and lets you break into the
debugger.

Globalization
• The AJAX server and client architecture in ASP.NET provides a model for
localizing and globalizing client script. This enables you to design applications
that use a single code base to provide UI for many locales (languages and
cultures). For example, the AJAX architecture enables JavaScript code to format
Date or Number objects automatically according to culture settings of the user's
browser, without requiring a postback to the server.

AJAX Server Architecture


The server pieces that support AJAX development consist of ASP.NET Web server
controls and components that manage the UI and flow of an application. The server
pieces also manage serialization, validation, control extensibility, and so on. There are
also ASP.NET Web services that enable you to access ASP.NET application services for
forms authentication, roles, and user profiles.

Script Support
• AJAX features in ASP.NET are implemented by using supporting scripts that are
sent from the server to the client. Depending on what AJAX features that you
enable, different scripts are sent to the browser.
• You can also create custom client script for your ASP.NET applications. In that
case, you can also use AJAX features to manage your custom script as static .js
files (on disk) or as .js files embedded as resources in an assembly.
• ASP.NET AJAX features include a model for release and debug modes. Release
mode provides error checking and exception handling that is optimized for
performance, with minimized script size. Debug mode provides more robust
debugging features, such as type and argument checking. ASP.NET runs the
debug versions when the application is in debug mode. This enables you to throw
exceptions in debug scripts while minimizing the size of release code.
• Script support for AJAX in ASP.NET is used to provide two important features:
• The Microsoft AJAX Library, which is a type system and a set of JavaScript
extensions that provide namespaces, inheritance, interfaces, enumerations,
reflection, and additional features
• Partial-page rendering, which updates regions of the page by using an
asynchronous postback.

Localization
• The ASP.NET AJAX architecture builds on the foundation of the ASP.NET 2.0
localization model. It provides additional support for localized .js files that are
embedded in an assembly or that are provided on disk. ASP.NET can serve
localized client scripts and resources automatically for specific languages and
regions.

Web Services
• With AJAX functionality in an ASP.NET Web page, you can use client script to
call both ASP.NET Web services (.asmx) and Windows Communication
Foundation (WCF) services (.svc). The required script references are
automatically added to the page, and they in turn automatically generate the Web
service proxy classes that you use from client script to call the Web service.
• You can also access ASP.NET Web services without using ASP.NET AJAX server
controls (for example, if you are using a different Web development
environment). To do so, in the page you can manually include references to the
Microsoft AJAX Library, to script files, and to the Web service itself. At run time,
ASP.NET generates the proxy classes that you can use to call the services
Application Services
• Application services in ASP.NET are built-in Web services that are based on
ASP.NET forms authentication, roles, and user profiles. These services can be
called by client script in an AJAX-enabled Web page, by a Windows client
application, or by a WCF-compatible client.

Server Controls
• ASP.NET AJAX server controls consist of server and client code that integrate to
produce rich client behavior. When you add an AJAX control to an ASP.NET Web
page, the page automatically sends supporting client script to the browser for
AJAX functionality. You can provide additional client code to customize the
functionality of a control, but this is not required.

The following list describes the most frequently used ASP.NET AJAX server controls.
ScriptManager
• Manages script resources for client components, partial-page rendering,
localization, globalization, and custom user scripts.
• The ScriptManager control is required in order to use the UpdatePanel ,
UpdateProgress and Timer controls.
UpdatePanel
• Enables you to refresh selected parts of the page, instead of refreshing the whole
page by using a synchronous postback.
UpdateProgress
• Provides status information about partial-page updates in UpdatePanel controls.
Timer
• Performs postbacks at defined intervals. You can use the Timer control to post the
whole page, or use it together with the UpdatePanel control to perform partial-
page updates at a defined interval.

You can also create custom ASP.NET server controls that include AJAX client behaviors.
Custom controls that enhance the capabilities of other ASP.NET Web controls are
referred to as extender controls.

The current code will look like ordinary ASP.NET, with a few new web controls. The
markup: Using ASP.NET AJAX Enabled Website

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Hello, world!</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="HelloWorldPanel">
<ContentTemplate>
<asp:Button runat="server" id="SayHelloButton" text="Hello, world!"
onclick="SayHelloButton_Click" />
<br /><br />
<asp:Label runat="server" id="HelloWorldLabel" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
In the CodeBehind, there's nothing new except for this event which you should add:
protected void SayHelloButton_Click(object sender, EventArgs e)
{
HelloWorldLabel.Text = "Hello, world! A random number: " + new
Random().Next().ToString();
}

Nothing fancy here, really. When we create the new website, a Default.aspx file is created
for us, including the ScriptManager control.

ScriptManager control
The ScriptManager control manages client script for AJAX-enabled ASP.NET Web
pages. By default, the ScriptManager control registers the script for the Microsoft AJAX
Library with the page. This enables client script to use the type system extensions and to
support features such as partial-page rendering and Web-service calls.

Scenarios
You must use a ScriptManager control on a page to enable the following AJAX features
of ASP.NET:
• Client-script functionality of the Microsoft AJAX Library, and any custom script
that you want to send to the browser. For more information, see Creating Custom
Client Script by Using the Microsoft AJAX Library.
• Partial-page rendering, which enables regions on the page to be independently
refreshed without a postback. The ASP.NET UpdatePanel, UpdateProgress, and
Timer controls require a ScriptManager control in order to support partial-page
rendering.
• JavaScript proxy classes for Web services, which enable you to use client script to
access Web services and specially marked methods in ASP.NET pages. It does this
by exposing the Web services and page methods as strongly typed objects.
• JavaScript classes to access ASP.NET authentication, profile, and roles
application services.
Background
• When a page contains one or more UpdatePanel controls, the ScriptManager
control manages partial-page rendering in the browser. The control interacts with
the page life cycle to update the parts of the page that are inside UpdatePanel
controls. For more information, see Partial-Page Rendering Overview.
• The EnablePartialRendering property of the ScriptManager control determines
whether a page participates in partial-page updates. By default, the
EnablePartialRendering property is true. Therefore, by default partial-page
rendering is enabled when you add a ScriptManager control to the page. For
information about how to use the UpdatePanel control with the ScriptManager
control, see Introduction to the UpdatePanel Control and Creating a Simple
ASP.NET Page with Multiple UpdatePanel Controls.

Handling Partial-page Rendering Errors


• During partial-page rendering, you can handle errors by doing the following:
• Set the AllowCustomErrorsRedirect property. This determines how the custom
error section of the Web.config file is used when an error occurs during an
asynchronous postback.
• Handle the ScriptManager control's AsyncPostBackError event, which is raised
when there is a page error during an asynchronous postback.
• Set the AsyncPostBackErrorMessage property, which is the error message that is
sent to the browser.
• Only one instance of the ScriptManager control can be added to the page. The
page can include the control directly, or indirectly inside a nested component such
as a user control, content page for a master page, or nested master page. If a page
already contains a ScriptManager control, but a nested or parent component needs
additional features of the ScriptManager control, the component can include a
ScriptManagerProxy control. For example, the ScriptManagerProxy control
enables you to add scripts and services that are specific to nested components.

This control should be used on every page where you wish to use AJAX, since it creates
basic AJAX support on your page, besides giving some more advanced possibilities,
which we will look into later on. After the manager, we have one of the most used
controls when working with AJAX, the UpdatePanel. This control allows you to wrap
markup which you would like to allow to be partially updated, that is, updated without
causing a real postback to the server. More about the UpdatePanel in a coming chapter.
Besides those two controls, everything else is standard controls, with no modifications
that would indicate alternate behavior.

Try running the example site, and click the button. The label will be updated with our
usual Hello world text, and a random number. Try repeatedly clicking the button, and you
will see the label get a new number each time. Notice the wonderful absence of a
blinking window and a running status bar - everything is done without updating anything
but the label! We've just created our first AJAX enabled page. If you wish to see how this
page would work without AJAX, try setting the "enablepartialrendering" of the
ScriptManager to false like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" enablepartialrendering="false"
/>
This will disallow the use of partial rendering on the page, and show you how it would
work without AJAX.

UpdatePanel control
ASP.NET UpdatePanel controls enable you to build rich, client-centric Web applications.
By using UpdatePanel controls, you can refresh selected parts of the page instead of
refreshing the whole page with a postback. This is referred to as performing a partial-
page update. An ASP.NET Web page that contains a ScriptManager control and one or
more UpdatePanel controls can automatically participate in partial-page updates, without
custom client script.

Scenarios
• The UpdatePanel control is a server control that helps you develop Web pages
with complex client behavior that makes a Web page appear more interactive to
the end user. Writing code that coordinates between server and client to update
only specified parts of a Web page usually requires in-depth knowledge of
ECMAScript (JavaScript).
• However, by using the UpdatePanel control, you can enable a Web page to
participate in partial-page updates without writing any client script. If you want,
you can add custom client script to enhance the client user experience. When you
use an UpdatePanel control, the page behavior is browser independent and can
potentially reduce the amount of data that is transferred between client and server.

Background
• UpdatePanel controls work by specifying regions of a page that can be updated
without refreshing the whole page. This process is coordinated by the
ScriptManager server control and the client PageRequestManager class.
• When partial-page updates are enabled, controls can asynchronously post to the
server. An asynchronous postback behaves like a regular postback in that the
resulting server page executes the complete page and control life cycle.
• However, with an asynchronous postback, page updates are limited to regions of
the page that are enclosed in UpdatePanel controls and that are marked to be
updated. The server sends HTML markup for only the affected elements to the
browser. In the browser, the client PageRequestManager class performs
Document Object Model (DOM) manipulation to replace existing HTML with
updated markup.
When you are using asynchronous postbacks or using the XMLHTTPRequest object, a
postback error can occur if the URL contains a double-byte character. You can resolve this
problem by including a <base href="url"/> element in the head element of the page, where
the href attribute is set to the URL-encoded string that references the page. You can add
this element added dynamically in server code.
The following illustration shows a page that is loaded for the first time, and a subsequent
asynchronous postback that refreshes the content of an UpdatePanel control.
Partial-page rendering overview

The UpdatePanel control requires a ScriptManager control in the Web page. By default,
partial-page updates are enabled because the default value of the EnablePartialRendering
property of the ScriptManager control is true.

Specifying UpdatePanel Control Content


You add content to an UpdatePanel
control declaratively or in the designer by using the ContentTemplate
property. In markup, this property is exposed as a ContentTemplate element. To add
content programmatically, you use the ContentTemplateContainer property.
When a page that contains one or more UpdatePanel controls is first rendered, all the
contents of the UpdatePanel controls are rendered and sent to the browser. On
subsequent asynchronous postbacks, the content of individual UpdatePanel controls
might be updated. Updates depend on the panel settings, on what element caused the
postback, and on code that is specific to each panel.

Specifying UpdatePanel Triggers


• By default, any postback control inside an UpdatePanel control causes an
asynchronous postback and refreshes the panel's content. However, you can also
configure other controls on the page to refresh an UpdatePanel control. You do
this by defining a trigger for the UpdatePanel control. A trigger is a binding that
specifies which postback control and event cause a panel to update. When the
specified event of the trigger control is raised (for example, a button's Click
event), the update panel is refreshed.
• The trigger is defined by using the asp:AsyncPostBackTrigger element inside the
Triggers element of the UpdatePanel control. (If you are editing the page in Visual
Studio, you can create triggers by using the UpdatePanelTrigger Collection
Editor dialog box.)
• A trigger's control event is optional. If you do not specify an event, the trigger
event is the default event of the control. For example, for the control, the default
event is the Click event.

How UpdatePanel Controls Are Refreshed


• The following list describes the property settings of the UpdatePanel control that
determine when a panel's content is updated during partial-page rendering.
• If the UpdateMode property is set to Always , the control’s content is updated on
every postback that originates from anywhere on the page. This includes
asynchronous postbacks from controls that are inside other UpdatePanel controls,
and postbacks from controls that are not inside UpdatePanel controls.
• If the UpdateMode property is set to Conditional, the UpdatePanel ontrol’s
content is updated when one of the following is true:
• When the postback is caused by a trigger for that UpdatePanel control.
• When you explicitly call the UpdatePanel control's Update method.
• When the UpdatePanel control is nested inside another UpdatePanel control and
the parent panel is updated.
• When the ChildrenAsTriggers property is set to true and any child control of the
UpdatePanel control causes a postback. Child controls of nested UpdatePanel
controls do not cause an update to the outer control unless they are explicitly
defined as triggers for the parent panel.
• If the ChildrenAsTriggers property is set to false and the UpdateMode property is
set to Always, an exception is thrown. The ChildrenAsTriggers property is
intended to be used only when the UpdateMode property is set to Conditional.

Using UpdatePanel Controls in Master Pages


• To use an UpdatePanel control in a master page, you must decide how to include
the ScriptManager control. If you include the ScriptManager control on the master
page, it can act as the ScriptManager control for all content pages. (If you want to
register scripts or services declaratively in a content page, you can add a control
to that content page.)
• If the master page does not contain the ScriptManager control, you can put the
ScriptManager control individually on each content page that contains an
UpdatePanel control. The design choice depends on how you intend to manage
client script in your application.
• In some cases, the ScriptManager control is on the master page and you do not
need partial-page rendering capabilities for a content page. In those cases, you
must programmatically set the EnablePartialRendering property of the
ScriptManager control to false for that content page.
• UpdatePanel controls can be nested. If the parent panel is refreshed, all nested
panels are refreshed also.

Controls that Are Not Compatible with UpdatePanel Controls


The following ASP.NET controls are not compatible with partial-page updates, and are
therefore not designed to work inside an UpdatePanel control:
• TreeView control under several conditions. One is when callbacks are enabled
that are not part of an asynchronous postback. Another is when you set styles
directly as control properties instead of implicitly styling the control by using a
reference to CSS styles. Another is when the EnableClientScript property is false
(the default is true). Another is if you change the value of the EnableClientScript
property between asynchronous postbacks. For more information, see TreeView
Web Server Control Overview.
• Menu control when you set styles directly as control properties instead of
implicitly styling the control by using a reference to CSS styles. For more
information, see Menu Control Overview .
• FileUpload and HtmlInputFile controls when they are used to upload files as part
of an asynchronous postback.
• GridView and DetailsView controls when their
EnableSortingAndPagingCallbacks property is set to true. The default is false.
• Login, PasswordRecovery, ChangePassword, and CreateUserWizard [controls
whose contents have not been converted to editable templates.
• The Substitution control.

To use a FileUpload or HtmlInputFile control inside an UpdatePanel control, set the


postback control that submits the file to be a PostBackTrigger control for the panel. The
FileUpload and HtmlInputFile control can be used only in postback scenarios.
All other controls work inside UpdatePanel controls. However, in some circumstances, a
control might not work as expected inside an UpdatePanel control. These circumstances
include the following:
• Registering script by calling registration methods of the ClientScriptManager
control.
• Rendering script or markup directly during control rendering, such as by calling
the Write method.
• If the control calls script registration methods of the ClientScriptManager control,
you might be able to use corresponding script registration methods of the
ScriptManager control instead. In that case, the control can work inside an
UpdatePanel control.

Using Web Parts Controls Inside UpdatePanel Controls


• ASP.NET Web Parts is an integrated set of controls for creating Web sites that
enable end users to modify the content, appearance, and behavior of Web pages
directly from a browser. You can use Web Parts controls inside UpdatePanel
controls with the following restrictions:
• Every WebPartZone control must be inside the same UpdatePanel control. For
example, you cannot have two UpdatePanel controls on the page, each with its
own WebPartZone] control.
• The WebPartManager control manages all client state information for Web Part
controls. It must be in the outermost UpdatePanel control on a page.
• You cannot import or export Web Parts controls by using an asynchronous
postback. (Performing this task requires a FileUpload control, which cannot be
used with asynchronous postbacks.) By default, importing Web Parts controls
performs a full postback.
• You cannot add or modify the styles of Web Parts controls during asynchronous
postbacks.

The <asp:UpdatePanel> tag has two childtags – ContentTemplate


Triggers tags.
The ContentTemplate tag is required, since it holds the content of the panel. The content
can be anything that you would normally put on your page, from literal text to web
controls.
The Triggers tag allows you to define certain triggers which will make the panel update
it's content. The following example will show the use of both childtags.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>UpdatePanel</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateButton2" eventname="Click" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateTimeLabel1" />
<asp:Button runat="server" id="UpdateButton1"
onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server" id="UpdatePanel1" updatemode="Conditional">
<ContentTemplate>
<asp:Label runat="server" id="DateTimeLabel2" />
<asp:Button runat="server" id="UpdateButton2"
onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Here is the CodeBehind. Just add the following method to the file:
protected void UpdateButton_Click(object sender, EventArgs e)
{
DateTimeLabel1.Text = DateTime.Now.ToString();
DateTimeLabel2.Text = DateTime.Now.ToString();
}

So, what's this example all about? Try running it, and click the two buttons. You will
notice that then first button updates only the first datestamp, while the second button
updates both. Why? We have set the Panels to update conditionally, which means that
their content is only updated if something insides them causes a postback, or if one of the
defined triggers are fired. As you can see, the first UpdatePanel carries a trigger which
references the second button. This will ensure that the first panel is updated even when a
control on a different UpdatePanel is used.
The AsyncPostBackTrigger tag is pretty simple - it only takes two attributes, the
controlid, a reference to the control which can trigger it, and the eventname, which tells
which eventtype can cause the trigger to fire. If you wish for the content of a
UpdatePanel to be updated no matter what, you may change the updatemode property to
Always.

In general, you should only have UpdatePanels around areas where you wish to do partial
updates. Don't wrap your entire page within an UpdatePanel, and don't be afraid to use
several panels, since this will give you more control of which areas update and when they
do it.

UpdateProgress control
The UpdateProgress control provides status information about partial-page updates in
UpdatePanel controls. You can customize the default content and the layout of the
UpdateProgress control. To prevent flashing when a partial-page update is very fast, you
can specify a delay before the UpdateProgress control is displayed.
Scenarios
• The UpdateProgress control helps you design a more intuitive UI when a Web
page contains one or more UpdatePanel controls for partial-page rendering. If a
partial-page update is slow, you can use the UpdateProgress control to provide
visual feedback about the status of the update. You can put multiple controls on a
page, each associated with a different UpdatePanel control. Alternatively, you can
use one UpdateProgress control and associate it with all UpdatePanel controls on
the page.

Background
• The UpdateProgress control renders a <div> element that is displayed or hidden
depending on whether an associated UpdatePanel control has caused an
asynchronous postback. For initial page rendering and for synchronous postbacks,
the UpdateProgress control is not displayed.

Associating an UpdateProgress Control with an UpdatePanel Control


• You associate an UpdateProgress control with an UpdatePanel control by setting
the AssociatedUpdatePanelID property of the UpdateProgress control. When a
postback event originates from an UpdatePanel control, any associated
UpdateProgress controls are displayed. If you do not associate the UpdateProgress
control with a specific UpdatePanel control, the UpdateProgress control displays
progress for any asynchronous postback.
• If the ChildrenAsTriggers property of a UpdatePanel control is set to false and an
asynchronous postback originates from inside that UpdatePanel control, any
associated UpdateProgress controls will be displayed.

Creating Content for the UpdateProgress Control


• Use the ProgressTemplate property to declaratively specify the message displayed
by an UpdateProgress control. The <ProgressTemplate> element can contain
HTML and markup. The following example shows how to specify a message for
an UpdateProgress control.

Specifying Content Layout


• When the DynamicLayout property is true, the UpdateProgress control initially
occupies no space in the page display. Instead, the page dynamically changes to
display the UpdateProgress control contents when needed. To support dynamic
display, the control is rendered as a <div> element that has its display style
property initially set to none.
• When the DynamicLayout property is false, the UpdateProgress control occupies
space in the page display, even if the control is not visible. In that case, the <div>
element for the control has its display style property set to block and its visibility
initially set to hidden.
Putting UpdateProgress Controls on the Page
• You can put UpdateProgress controls inside or outside UpdatePanel controls. A
UpdateProgress control is displayed whenever the UpdatePanel control it is
associated with is updated as a result of an asynchronous postback. This is true
even if the UpdateProgress control is inside another UpdatePanel control.
• If an UpdatePanel control is inside another update panel, a postback that
originates inside the child panel causes any UpdateProgress controls associated
with the child panel to be displayed. It also displays any UpdateProgress controls
associated with the parent panel. If a postback originates from an immediate child
control of the parent panel, only the UpdateProgress controls associated with the
parent panel are displayed. This follows the logic for how postbacks are triggered.

Specifying When UpdateProgress Controls Are Displayed


• You can programmatically control when an UpdateProgress control is displayed
by using the JavaScript beginRequest and endRequest events of the
PageRequestManager class. In the beginRequest event handler, display the
DOM element that represents the UpdateProgress control. In the endRequest
event handler, hide the element.
• You must provide client script to show and hide an UpdateProgress control in the
following circumstances:
• During a postback from a control that is registered as an asynchronous postback
trigger for the update panel, but that the UpdateProgress control is not associated
with.
• During postbacks from controls that are registered programmatically as
asynchronous postback controls by using the RegisterAsyncPostBackControl
method of the ScriptManager control. In that case, the UpdateProgress control
cannot determine automatically that an asynchronous postback has been triggered.

One of the problems with Ajax, is the fact that since it's asynchronus and in the
background, the browser will not show you any status. With fast servers and fast
methods, this is not a big problem, but whenever you have a method which takes up a bit
of time, the user is very likely to get impatient. Fortunately, ASP.NET AJAX solves this
problem for us as well, with a nice control called UpdateProgress. It will use your own
template to show that an asynchronus method is working. Have a look at the following
example, which will show the control in action. It will be explained afterwards.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>UpdateProgress control</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdateProgress runat="server" id="PageUpdateProgress">
<ProgressTemplate>
Loading...
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" id="Panel">
<ContentTemplate>
<asp:Button runat="server" id="UpdateButton" onclick="UpdateButton_Click"
text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
The following method should be added to your CodeBehind file:
protected void UpdateButton_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
This simple example will just show you how easy it is to use the UpdateProgress control.
Once the button is clicked, the script sleeps for 5 seconds (don't use code like that in your
real projects - it's for demonstrational purposes only!), and the "Loading..." text is
displayed on your page. You can use anything in the ProgressTemplate, including
ordinary markup and other controls. A common use is an animated GIF, positioned
strategically on the page using CSS positioning.

You can have multiple UpdateProgress controls on the page, and by using the
AssociatedUpdatePanelID property, you can make sure that the UpdateProgress is only
shown when a certain UpdatePanel is updated.

The DynamicLayout property is nice to know as well. It tells whether or not the page
should reserve space for your progress control. If it's set to true, which is the default, the
space is dynamic, hence it's not reserved, but taken when the control is shown. If you
wish to reserve the space, set this property to false. To see the difference, add the property
to our example and change it back and forth.

If some of your postbacks are fast, the UpdateProgress will only be shown for a very
short amount of time, resulting in a blinking behavior, which may confuse your users. For
that reason, you may specify a minimum amount of time to occur before showing the
progress control. This can be done with the DisplayAfter attribute. Specify a number of
milliseconds to elapse before showing the progress control, e.g. 2000 if you wish to wait
for 2 seconds.

Timer control
Timer controls allow you to do postbacks at certain intervals. If used together with
UpdatePanels, which is the most common approach, it allows for timed partial updates of
your page, but it can be used for posting back the entire page as well. In this chapter we
will focus on using timers with UpdatePanels, so if you haven't already read the chapter
on UpdatePanels, please do so now.

Here is a small example of using the Timer control. It simply updates a timestamp every
5 seconds.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Timers</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000"
ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
We only have a single CodeBehind function, which you should add to your CodeBehind
file:
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
}
This is all very simple. We have a normal UpdatePanel, which carries a Trigger reference
to our new Timer control. This means that the panel is updated when the Timer "ticks",
that is, fires the Tick event. The Timer control uses the interval attribute to define the
number of milliseconds to occur before firing the Tick event. As you can see from our
CodeBehind code listing, we just update the DateStampLabel each time the Timer fires.
This could be done more efficient with a simple piece of JavaScript, which updates the
time on the clientside instead of involving the server. The example is only used to
demonstrate the potential of the Timer control.
Another approach is including the Timer inside the UpdatePanel. Doing so would save us
from defining a trigger, but you should be aware of the fact that the behavior will be
different, depending on whether you have the Timer inside or outside an UpdatePanel.
When a Timer is inside an UpdatePanel, the Timer is not re-constructed until the
UpdatePanel is fully updated. That means that if you have a Timer with an interval of 60
seconds, and the update takes 5 seconds, the next event won't be fired 60 seconds after
the previous, but 65 seconds after. On the other hand, if the Timer is outside the
UpdatePanel, the user will only look at the content of the panel for 55 seconds before it's
updated again.

You should always remember that even though partial updates are not as heavy on the
server as real postbacks, the server is still contacted, and when using timers, you may get
a lot of partial postbacks, which can slow things down. Always use as high intervals as
possible, and consider if contacting the server is really necessary or not.

ASP.NET AJAX Client Life-Cycle Events

• A Microsoft ASP.NET AJAX page raises the same server life-cycle events as an
ASP.NET 2.0 Web page and also 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 ASP.NET 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.

Client Classes
• The two main Microsoft AJAX Library classes that raise events during the client
life cycle of an ASP.NET AJAX Web 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.

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 page contains a ScriptManager control, and the control's
SupportsPartialRendering and EnablePartialRendering property are both true.
• The request is a GET request.
• A response from the server is returned successfully.
The following client events occur, in this order:
• The initial request is sent to the server.
• The response is received by the client.
• The Application instance raises the init event.
• 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 page contains a ScriptManager control, and the control's
SupportsPartialRendering and EnablePartialRendering properties are both true.
• The page contains an UpdatePanel control, and the control's ChildrenAsTriggers
property is true.
• A button inside the UpdatePanel control initiates an asynchronous postback.
• A response from the server is returned successfully.
The following client events occur, in this order:
• The button inside the UpdatePanel is clicked, which initiates an asynchronous
postback.
• The PageRequestManager instance raises the initializeRequest event.
• The PageRequestManager instance raises the beginRequest event.
• The request is sent to the server.
• The response is received by the client.
• The PageRequestManager instance raises the pageLoading event.
• The PageRequestManager instance raises the pageLoaded event.
• The Application instance raises the load event.
• The PageRequestManager instance raises the endRequest event.

• Note that the load event of the Application instance is raised after the
PageRequestManagerpageLoaded 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:
• A button inside the UpdatePanel is clicked, which initiates an asynchronous
postback.
• The PageRequestManager instance raises the initializeRequest event.
• The PageRequestManager instance raises the beginRequest event.
• The request is sent to the server.
• The button is clicked again, which initiates a second asynchronous postback.
• The PageRequestManager instance raises the initializeRequest event for the
second button click.
• The PageRequestManager instance raises the endRequest event for the first button
click.
• The PageRequestManager instance raises the beginRequest event for the second
button click.
• The request initiated by the second click is sent to the server.
• The response is received for the second click.
• The PageRequestManager instance raises the pageLoading event.
• The PageRequestManager instance raises the pageLoaded event.
• The Application instance raises the load event.
• 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.

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 page contains a ScriptManager control and the control's
SupportsPartialRendering and EnablePartialRendering property are both true.
• The target page exists.
The following client events are raised, in this order:
• The request for new page is initiated.
• The response for the new page is received by the browser.
• The Application instance raises the unload event.
• 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.