You are on page 1of 70

ASP.

NET AJAX Overview


Introduction
Microsoft ASP.NET AJAX enables you to quickly create Web pages that include a rich user experience
with responsive and familiar user interface (UI) elements. ASP.NET AJAX provides client-script
libraries that incorporate cross-browser ECMAScript (JavaScript) and dynamic HTML (DHTML)
technologies, and it integrates them with the ASP.NET 2.0 server-based development platform. By
using ASP.NET AJAX, you can improve the user experience and the efficiency of your Web
applications.

Why Use ASP.NET AJAX?


ASP.NET AJAX enables you to build rich Web applications that have many advantages over Web
applications that are completely server-based. ASP.NET AJAX applications offer:

Improved efficiency by performing significant parts of a Web page's processing 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 and user
profiles.

Integration of data from different sources through calls to Web services.


A framework that simplifies customization 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.

ASP.NET AJAX Architecture


ASP.NET AJAX consists of client-script libraries and of server components that are integrated to
provide a robust development framework. In addition to ASP.NET AJAX, you can use the ASP.NET
AJAX Control Toolkit and the features in the ASP.NET AJAX Futures releases, which are both
community supported.

The following illustration shows the functionality that is included in the client-script libraries and
server components.

ASP.NET AJAX server and client architecture


The illustration shows the functionality of the client-based Microsoft AJAX Library, which includes
support for creating client components, browser compatibility, and networking and core services.
The illustration also shows functionality of server-based ASP.NET 2.0 AJAX Extensions, which
includes script support, Web services, application services, and server controls.

ASP.NET AJAX Server Architecture


The ASP.NET AJAX server components consist of ASP.NET Web server controls and components to
manage the UI and flow of an application, and to 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 and user profiles.

ASP.NET AJAX Server Controls


The ASP.NET AJAX server controls consist of server and client code that integrate to produce AJAXlike behavior. 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.

ASP.NET AJAX Web Services


ASP.NET AJAX provides Web services that you can use from client script to work with ASP.NET
application services for forms authentication and user profiles. This enables you to use client script
to help protect resources by using forms authentication and to persist user-specific settings on the
server. In addition, ASP.NET AJAX includes network components that make it easy to return results
from any Web service call. For information and examples, see Asynchronous Communication Layer
Overview and ASP.NET Application Services.

ASP.NET AJAX Server Control Extensibility


ASP.NET AJAX enables you to create custom ASP.NET AJAX server controls that include client
behaviors. For more information, see the tutorials in ASP.NET AJAX Extensibility and the Microsoft
ASP.NET AJAX Control Toolkit.

ASP.NET AJAX Client Architecture


The ASP.NET AJAX client-script libraries consist of JavaScript (.js) files that provide features for
object-oriented development. The object-oriented features included in the ASP.NET AJAX clientscript libraries enable a high level of consistency and modularity in client scripting. The following
layers are included in the ASP.NET AJAX script libraries:

A browser compatibility layer. This provides compatibility across the most frequently used
browsers (including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari) for your
ASP.NET AJAX scripts.

ASP.NET AJAX core services, which include extensions to JavaScript, such as classes,
namespaces, event handling, inheritance, data types, and object serialization.

An ASP.NET AJAX base class library, which includes components such as string builders and
extended error handling.

A networking layer that handles communication with Web-based services and applications,
and that manages asynchronous remote method calls.

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 solve versioning issues.

Support for accessing server-based forms authentication 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.

Support for release and debug modes and localization support for both assembly-embedded
and standalone JavaScript files. For more information, see the ASP.NET AJAX Debugging
and Tracing Overview and Localizing Resources for Component Libraries Overview.

Debugging
The ASP.NET AJAX architecture provides a model for release and debug modes. Release mode
provides error checking and exception handling optimized for performance, with minimized script
size. Debug mode provides more robust debugging features, such as type and argument checking.
If you create debug versions of custom client scripts or script resources, 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.
A debug helper class, Sys.Debug, provides methods for displaying objects in readable form at the
end of a Web page. It also shows trace messages, enables you to use assertions, and lets you break
into the debugger. An extended Error Object object API provides helpful exception details with
support for release and debug modes.

For more information, see the ASP.NET AJAX Debugging and Tracing Overview and
Localizing Resources for Component Libraries Overview.

Localization and Globalization


The ASP.NET AJAX server and client architecture 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, ASP.NET AJAX 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
ASP.NET AJAX builds on the foundation of the ASP.NET 2.0 localization model. It provides additional
support for localized script files that are embedded in an assembly or that are provided as .js files

on disk. ASP.NET AJAX can serve localized client scripts and resources automatically for specific
languages and regions.
For more information, see the following topics:

Localizing Resources for Component Libraries Overview


Embedding Localized Resources for a JavaScript File
Globalizing a Date by Using Client Script

ASP.NET AJAX Control Toolkit


The ASP.NET AJAX Control Toolkit is a collection of samples and components that show you some of
the experiences you can create with rich client ASP.NET AJAX controls and extenders. The Control
Toolkit provides samples and a powerful SDK to make it simple to create and reuse custom controls
and extenders. You can download the ASP.NET AJAX Control Toolkit from the ASP.NET Ajax Web site.
The ASP.NET AJAX Control Toolkit is community supported.

ASP.NET AJAX Community-supported Futures Releases


The ASP.NET AJAX community-supported Futures releases provide features that extend the core
ASP.NET AJAX platform with functionality that remains under development and that is not included
in the Microsoft ASP.NET AJAX release. This includes additional extender controls, support for client
declarative syntax (xml-script), and more. To download and learn more about the Futures
release, see the ASP.NET AJAX Web site.

See Also
Installing ASP.NET AJAX
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

The UpdatePanel and UpdateProgress Controls


Introduction

Partial-page rendering makes it unnecessary for the whole ASP.NET page to be refreshed as the
result of a postback. Instead, only the region of the page that has to be refreshed is updated. As a
result, users do not see the whole page reload with every postback, which makes user interaction
with the Web page more seamless.

In This Section
Partial-Page Rendering Overview
Describes partial-page rendering and its components.
UpdatePanel Control Overview
Describes the UpdatePanel control, which identifies a region of the page as updatable using
partial-page rendering.
UpdateProgress Control Overview
Describes the UpdateProgress control, which enables you to display status to users while an
asynchronous request is pending.
PageRequestManager Class Overview
Describes the client PageRequestManager class, which manages partial-page rendering in
the browser and enables you to customize partial-page rendering behavior.

See Also

Partial-Page Rendering Overview


Introduction
Partial-page rendering removes the need for the whole page to be refreshed as the result of a
postback. Instead, only individual regions of the page that have changed are updated. As a result,
users do not see the whole page reload with every postback, which makes user interaction with the
Web page more seamless. Microsoft ASP.NET AJAX enables you to add partial-page rendering to new
or existing ASP.NET Web pages without writing client script.
This topic contains the following sections:

Scenarios
Features
Background

Code Examples
Class Reference

Scenarios
ASP.NET AJAX enables you to extend existing ASP.NET 2.0 applications and to develop new ones
that incorporate AJAX (Asynchronous JavaScript and XML) functionality. Use ASP.NET AJAX when
you want to do the following:

Improve the user experience with Web pages that are richer, that are more responsive to
user actions, and that behave like traditional client applications.

Reduce full-page refreshes and avoid page flicker.


Enable cross-browser compatibility without writing client script.
Perform AJAX-style client/server communication without writing client script.
Use the controls and components from the ASP.NET AJAX Control Toolkit.
Develop custom Microsoft ASP.NET AJAX controls.

Partial-Page Rendering Features


Partial-page rendering relies on server controls in ASP.NET AJAX and on client functions in the
Microsoft AJAX Library. You do not have to use the Microsoft AJAX Library to enable partial-page
rendering, because this functionality is provided automatically when you use the ASP.NET
AJAX server controls. However, you can use the APIs exposed in the client library for additional
AJAX functionality.
The primary features of ASP.NET AJAX that support partial-page rendering include the following:

A declarative model that works like ASP.NET server controls. In many scenarios, you can
specify partial-page rendering using only declarative markup.

Server controls that perform the underlying tasks required for partial-page updates. These
include the ScriptManager control and the UpdatePanel control.

Integration between ASP.NET AJAX server controls and the Microsoft AJAX Library for
common tasks. These tasks include enabling users to cancel a postback, displaying custom

progress messages during an asynchronous postback, and determining how concurrent


asynchronous postbacks are processed.

Error-handling options for partial-page rendering, which enable you to customize how errors
are displayed in the browser.

Cross-browser compatibility, which is built into the Microsoft AJAX Library. Simply using the
server controls automatically invokes the correct browser functionality.

Background
Typical Web pages built with ASP.NET Web server controls perform postbacks initiated by a user
action on the page, such as clicking a button. In the response, the server renders a new page.
Frequently this re-renders controls and text that did not change between postbacks.
With ASP.NET AJAX partial-page rendering, you can refresh individual regions of the page
asynchronously and make the page more responsive to the user. You can implement partial-page
rendering using ASP.NET Web server controls, and optionally write client script that uses the APIs in
the Microsoft AJAX Library.

Server Controls for Partial-Page Updates


To add AJAX functionality to ASP.NET Web pages, you identify individual sections of the page that
you want to update. You then put the content of these sections into UpdatePanel controls. The
contents of an UpdatePanel control can be HTML or other ASP.NET controls. You can add an
UpdatePanel control to the page as you would any other control. For example, in Visual Studio you
can drag it from the toolbox to the Web page, or you can add it by using declarative markup in the
page. The following example shows the markup for an UpdatePanel control.

CS
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- Place updatable markup and controls here. -->
</ContentTemplate>
</asp:UpdatePanel>

VB
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- Place updatable markup and controls here. -->
</ContentTemplate>
</asp:UpdatePanel>
By default, postbacks that originate from controls inside the update panel (child controls)
automatically initiate asynchronous postbacks and cause a partial-page update. You can also specify

that controls outside the update panel cause an asynchronous postback and that they refresh the
UpdatePanel control's content. A control that causes an asynchronous postback is referred to as a
trigger. For more information about triggers, see Creating a Simple ASP.NET Page with Multiple
UpdatePanel Controls.
An asynchronous postback behaves much like a synchronous postback. All the server page life-cycle
events occur, and view state and form data are preserved. However, in the rendering phase, only
the contents of the UpdatePanel control are sent to the browser. The rest of the page remains
unchanged.
To support partial-page rendering, you must put a ScriptManager control on the page. The
ScriptManager control keeps track of all the update panels on the page and of their triggers. It
coordinates partial-page rendering behavior on the server, and determines which sections of the
page to render as a result of an asynchronous postback.
The following example shows an UpdatePanel control whose content is refreshed whenever a
postback originates from inside the panel.
Run View
For more examples of how to use UpdatePanel controls to enable partial-page rendering, see the
topics listed in the Code Examples section.

Using Client Script for Partial-Page Updates


The ECMAScript (JavaScript) PageRequestManager class in the Microsoft AJAX Library supports
partial-page updates. It runs in the browser to manage the response to asynchronous postbacks
and to update content in individual regions. You do not have to do anything to enable this
functionality. It occurs automatically when you add one or more UpdatePanel controls and a
ScriptManager control to the page.
You can also use JavaScript and the PageRequestManager class to customize partial-page updates
on a page. For example, you can write script to give precedence to a specific asynchronous postback
if more than one is underway. You can also enable users to cancel postbacks that are in progress.
The following example shows client script that provides an event handler that is called when the
page finishes loading.

CS
<script type="text/javascript" language="javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(PageLoadedEventHandler);
function PageLoadedEventHandler() {
// custom script
}
</script>

VB
<script type="text/javascript" language="javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(PageLoadedEventHandler);
function PageLoadedEventHandler() {
// custom script
}
</script>
For more information about how to use the Microsoft AJAX Library for partial-page rendering, see
Working with PageRequestManager Events and PageRequestManager Class Overview.

Enabling Partial-Page Rendering Support


You enable or disable partial-page rendering for a page by setting the EnablePartialRendering
property of the ScriptManager control. You can also specify whether partial-page rendering is
supported for a page by setting the SupportsPartialRendering property of the ScriptManager control.
If you do not set the SupportsPartialRendering property and if the EnablePartialRendering property
is true (which is the default), the capabilities of the browser are used to determine whether partialpage rendering is supported.
If partial-page rendering is not enabled for a page, if it has been disabled, or if it is not supported in
a browser, the page uses fallback behavior. Actions that ordinarily would perform an asynchronous
postback instead perform a synchronous postback and update the whole page. Any UpdatePanel
controls on the page are ignored, and their contents are rendered as if they were not inside an
UpdatePanel control.
note
ASP.NET Web pages that are configured for legacy rendering are not supported in ASP.NET AJAX. For
more information, see ASP.NET and XHTML.

Code Examples
The following example shows partial-page rendering in action. There are two UpdatePanel controls.
One control takes user input and another displays a summary of the input.
Run View

How-to and Walkthrough Topics


Introduction to the UpdatePanel Control
Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls
Using the UpdatePanel Control with Data-Bound Controls

10

Using the UpdatePanel Control with Master Pages


Customizing Error Handling for UpdatePanel Controls
Working with PageRequestManager Events
Animating UpdatePanel Controls
Canceling an Asynchronous Postback
Giving Precedence to a Specific Asynchronous Postback

Class Reference
The following table lists the key server classes for partial-page rendering.

Class

Description

UpdatePanel

Specifies regions of the page to be updated during partial-page rendering.

ScriptManager

Manages ASP.NET AJAX components, partial-page rendering, client


requests, and server responses on ASP.NET Web pages.

ScriptManagerProxy Enables nested components to add script and service references to pages
that already contain a ScriptManager control in a parent element.
The following table lists the key client class for partial-page rendering.

Class

Description

PageRequestManager

Manages client partial-page rendering and exposes members for

Class

custom client scripting.

See Also
UpdatePanel Control Overview
PageRequestManager Class Overview
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

11

UpdatePanel Control Overview


Introduction
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. A Web page that
contains a ScriptManager control and one or more UpdatePanel controls can automatically
participate in partial-page updates, without custom client script.
This topic contains information about the following:
Scenarios
Background
Code Examples
Class Reference

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. Coordinating 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. The following illustration

12

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

Enabling Partial-Page Updates


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.
The following example shows markup that defines a ScriptManager control and an UpdatePanel
control on a page. The UpdatePanel control contains a Button control that refreshes the content
inside the panel when you click it. By default, the ChildrenAsTriggers property is true. Therefore,
the Button control acts as an asynchronous postback control.
Run View

13

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 following example shows how to specify a trigger for an UpdatePanel control.
Run View
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 Button 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 UpdatePanel controls 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 controls content is updated
when one of the following is true:
When the postback is caused by a trigger for that UpdatePanel control.

14

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 UpdatePanel 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 ScriptManagerProxy 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. For more information about
how to manage client script, see ScriptManager Control Overview. For more information about
master pages, see ASP.NET Master Pages Overview.
If the ScriptManager control is on the master page and you do not need partial-page rendering
capabilities for a content page, you must programmatically set the EnablePartialRendering property
of the ScriptManager control to false for that content page.
The following example shows markup for a ScriptManager control on the master page and an
UpdatePanel control on a content page. In this example, a property named LastUpdate is defined
on the master page and is referenced from inside the UpdatePanel control.
Run View

Using Nested UpdatePanel Controls


UpdatePanel controls can be nested. If the parent panel is refreshed, all nested panels are refreshed
also.
The following example shows markup that defines an UpdatePanel control inside another
UpdatePanel control. A button in the parent panel triggers an update of the content in both the
parent and the child panel. The button in the child panel triggers an update of only the child panel.

15

Run View
The following example shows a nested UpdatePanel control with a GridView control. The GridView
control is inside an UpdatePanel control, and each GridView row contains a nested GridView control
inside another UpdatePanel control.
Run View
When an inner GridView control displays a new page of records, the outer panel and the panels in
the other rows of the outer GridView control are not refreshed. When the outer GridView control
displays a new page of records, the outer panel and the nested panels are all refreshed.

Refreshing an UpdatePanel Programmatically


The following example shows how to refresh an UpdatePanel control programmatically. In this
example, a page registers a control as a trigger by calling the
RegisterAsyncPostBackControl(Control) method. The code refreshes the UpdatePanel control
programmatically by calling the Update() method.
Run View

Creating UpdatePanel Controls Programmatically


To add an UpdatePanel control to a page programmatically, you create a new instance of the
UpdatePanel control. You then add controls to it by using the ContentTemplateContainer property
and the Add(Control) method. Do not add controls directly to the ContentTemplate property.
When an UpdatePanel control is added programmatically, only postbacks from controls in the same
naming container as the UpdatePanel control can be used as triggers for the panel.
The following example shows how to programmatically add an UpdatePanel control to a page. The
example adds a Label and a Button control to the update panel by using the
ContentTemplateContainer property. Because the ChildrenAsTriggers property is true by default, the
Button control acts as a trigger for the panel.
Run View

Controls that Are Not Compatible with UpdatePanel Controls


The following ASP.NET controls are not compatible with partial-page updates, and are therefore not
supported inside an UpdatePanel control:

TreeView and Menu controls.

Web Parts controls. For more information, see ASP.NET Web Parts Controls.

16

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

Validation controls, which includes the BaseCompareValidator, BaseValidator,


CompareValidator, CustomValidator, RangeValidator, RegularExpressionValidator,
RequiredFieldValidator, and ValidationSummary control.
Controls that are incompatible with partial-page rendering can still be used on a page outside
UpdatePanel controls. Additionally, in some cases you can use the controls in a specific way to make
them compatible with partial-page updates. For example, you can use the Login, ChangePassword,
or PasswordRecovery controls inside an UpdatePanel control if you can convert their contents to
templates. (If you are using Visual Studio, in Design view you can convert the controls by using
smart-tag menu commands such as Convert to Template or Customize Create User Step.)
When you convert these controls into editable templates, the validation controls that are used in the
control are defined declaratively by using markup in the page. To make the validators compatible
with an UpdatePanel control, set the EnableClientScript property of the validators to false. This
disables the client script that would ordinarily be used to perform validation in the browser. As a
result, during an asynchronous postback, the validators perform validation on the server. However,
because only the content of the UpdatePanel is refreshed, the validators can provide the kind of
immediate feedback that is ordinarily provided by client script.
To use a FileUpload control inside an UpdatePanel control, set the postback control that submits the
file to be a PostBackTrigger control for the panel.
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(String) method.

If the control calls script registration methods of the ClientScriptManager control, you could use
corresponding script registration methods of the ScriptManager control instead. In that case, the
control can work inside an UpdatePanel control.

17

Code Examples
The following sections include examples that show how to create and use UpdatePanel controls.

How-to and Walkthrough Topics

Introduction to the UpdatePanel Control

Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls

Using the UpdatePanel Control with Data-Bound Controls

Using the UpdatePanel Control with Master Pages

Using the UpdatePanel Control with User Controls

Using the UpdatePanel Control with a Web Service

Customizing Error Handling for UpdatePanel Controls

Working with PageRequestManager Events

Animating UpdatePanel Controls

Canceling an Asynchronous Postback

Giving Precedence to a Specific Asynchronous Postback

Class Reference
The key server classes for UpdatePanel controls are shown in the following table.

Class

Description

UpdatePanel

A server control that specifies the parts of a Web page that can
participate in partial-page updates.

ScriptManager

A server control that manages partial-page rendering. The ScriptManager


control registers script components to send to the browser. It also
overrides page rendering so that only specified regions of the page are
rendered.

ScriptManagerProxy

A server control that enables nested components (such as content pages

18

or user controls) to add script and Web-service references. This control is


useful if the parent element already contains a ScriptManager control.
PageRequestManager A class in the Microsoft AJAX Library that coordinates partial-page
rendering in the browser. The PageRequestManager class asynchronously
exchanges information with the server, and exposes events and methods
for custom client script development.

Additional Topics
ASP.NET Page Life Cycle Overview

See Also

Introduction to the UpdatePanel Control


Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls
UpdateProgress Control Overview
Partial-Page Rendering Overview
PageRequestManager Class Overview
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

UpdateProgress Control Overview


Introduction
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.
This topic contains information about the following:

Scenarios
Background
Code Examples
Class Reference

19

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

CS
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
An update is in progress...
</ProgressTemplate>
</asp:UpdateProgress>

VB
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
An update is in progress...

20

</ProgressTemplate>
</asp:UpdateProgress>
The following example shows one UpdateProgress control that shows update status for two
UpdatePanel controls.
Run View
The following example shows two UpdateProgress controls. Each shows update status for an
associated UpdatePanel control.
Run View
The following example shows how to add a button to the <ProgressTemplate> element that the
user can click to stop the asynchronous postback. Any new postbacks that are initiated while
another postback is executing are canceled.
Run View
In the previous example, the onClick attribute of an HtmlButton control in the
<ProgressTemplate> element calls the JavaScript AbortPostBack function. For more information,
see the abortPostBack method and the isInAsyncPostBack property of the PageRequestManager
class.

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.

21

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(Control) method of the
ScriptManager control. In that case, the UpdateProgress control cannot determine
automatically that an asynchronous postback has been triggered.

Code Examples
The following sections include code examples for creating and using UpdateProgress controls.

How-to and Walkthrough Topics


Introduction to the UpdateProgress Control
Programming UpdateProgress Controls in Client Script

Class Reference
The following table lists the key classes for working with the UpdateProgress class.

Class

Description

UpdateProgress

Provides visual feedback in the browser when the content of UpdatePanel


controls is updated.

UpdatePanel

Specifies parts of a Web page that can participate in partial-page updates.

ScriptManager

Manages partial-page rendering. The ScriptManager control registers


script components to send to the browser and overrides page rendering
so that only specified regions of the page are rendered.

PageRequestManager Coordinates partial-page rendering in the browser. The


PageRequestManager class asynchronously exchanges information with

22

the server and exposes events and methods for custom client scripting.

Additional Topics
ASP.NET Page Life Cycle Overview

See Also

UpdatePanel Control Overview


Introduction to the UpdatePanel Control
Introduction to the UpdateProgress Control
Programming UpdateProgress Controls in Client Script
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

ASP.NET PageRequestManager Class Overview


Introduction
The PageRequestManager class in the Microsoft AJAX Library manages partial-page updates in the
browser. When a page contains a ScriptManager control and one or more UpdatePanel controls, the
page is automatically enabled for partial-page rendering. The PageRequestManager class exposes
properties, methods, and events that enable you to customize partial-page updates with client
script. The PageRequestManager class exposes a client page event model that you can use in a way
similar to how you use the server page event model.
This topic contains:

Scenarios
Features
Background
Code Examples
How-to and Walkthrough Topics
Class Reference

23

Scenarios
You can enable partial-page updates by using the ScriptManager and UpdatePanel Web server
controls. Partial-page updates require no client scripting. However, you can use the
PageRequestManager class and client script when you want to do the following:

Control how multiple asynchronous postbacks are processed. The default behavior is that
the last postback takes precedence. The PageRequestManager class enables you to give
precedence to a specific postback and cancel others that are underway.

Provide visual cues or other notification to mark regions on the page that have been
updated or created as a result of the last asynchronous postback. This can improve the user
experience, especially in scenarios where multiple UpdatePanel controls are used.

Display status messages during asynchronous postbacks. If postbacks take a long time to
process, you might want to show a progress indicator such as an animated image. You can
also give the user the option to cancel the postback.

Provide custom error-message handling for partial-page updates. If an unexpected error


occurs during an asynchronous postback, you can handle the error in client script.

Access the underlying request and response objects that are used for the asynchronous
postback.

Features
Features of partial-page updates in the Microsoft AJAX Library include the following:

Client page life-cycle events that are raised at key times during partial-page updates.
Information about which UpdatePanel controls were deleted, updated, or created during an
asynchronous postback.

Properties and methods that enable you to determine in client script whether the page is
processing an asynchronous postback. You can also use these methods to stop an
asynchronous postback that is underway or to cancel new postbacks.

Information about server data that is sent to controls that are not participating in partialpage updates.

Background

24

During partial-page updates initiated by asynchronous postbacks, the PageRequestManager class


coordinates how the page content is incrementally updated in the browser. The UpdatePanel server
control and PageRequestManager client class abstract much of the complexity of partial-page
updates. When you use client script and members of the PageRequestManager class, you can
customize the partial-page update behavior in the browser.

Partial-Page Update Event Handling


During page processing of both postbacks and asynchronous postbacks, you can handle browser
document object model (DOM) events to run custom script. For example, you can run script when
the browser loads or unloads the page.
However, these DOM events do not enable you to access all relevant information or to control the
behavior during asynchronous postbacks and during partial-page updates. Therefore, the
PageRequestManager class exposes the following events that enable you to customize partial-page
updates:

initializeRequest
beginRequest
pageLoading
pageLoaded
endRequest
For more information about these events, see Working with PageRequestManager Events.

Code Examples
The following example shows how to use the pageLoaded event of the PageRequestManager class to
animate an UpdatePanel control when the page is updated after an asynchronous postback. In this
example, users can select a date and enter an e-mail address into a form to make a ticket request.
When an asynchronous postback occurs (triggered by links outside the UpdatePanel control), the
panel is animated briefly to notify the user that the date value was entered into the text box. The
page contains a pop-up window that displays a Calendar control. The calendar is displayed or hidden
using the control's Visible property. The whole page does not have to be refreshed when the
calendar is displayed or hidden, or when a date is selected, because the Calendar control is inside
an UpdatePanel control.
Run View

25

How-to and Walkthrough Topics


Working with PageRequestManager Events
Animating UpdatePanel Controls
Canceling an Asynchronous Postback
Giving Precedence to a Specific Asynchronous Postback
Customizing Error Handling for UpdatePanel Controls

Class Reference
The following table lists the classes that relate to the PageRequestManager class.

Class

Description

PageRequestManager Class Manages client partial-page updates and exposes members for
custom client scripting.
InitializeRequestEventArgs

Provides event data for the initializeRequest event, which is raised

Class

before the asynchronous request starts.

BeginRequestEventArgs

Provides event data for the beginRequest event, which is raised

Class

after an asynchronous postback starts and before the postback is


sent to the server.

PageLoadingEventArgs

Provides event data for the pageLoading event, which is raised after

Class

the response to an asynchronous postback is received, but before


any content on the page is updated. This event is not raised if the
postback is stopped or if an unhandled exception is thrown on the
server during processing.

PageLoadedEventArgs Class Provides event data for the pageLoaded event, which is raised after
all content on the page is refreshed, whether as the result of a
synchronous postback or an asynchronous postback. This event is
not raised if the postback is stopped or if an unhandled exception is
thrown on the server during processing.
EndRequestEventArgs Class Provides event data for the endRequest event, which is raised after
an asynchronous postback has finished.

See Also

26

UpdatePanel Control Overview


PageRequestManager Class Overview
Asynchronous Communication Layer Overview
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

ScriptManager Control Overview


Introduction
The ScriptManager control manages client script for Microsoft ASP.NET AJAX 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.
This topic contains the following sections:

Why Use the ScriptManager Control


Using Type System Extensions
Enabling Partial-Page Rendering
Registering Custom Script
Registering Web Services
Using Authentication and Profile Services from Client Script
The ScriptManagerProxy Control
Class Reference

Why Use the ScriptManager Control


You must use a ScriptManager control on a page to enable the following features of ASP.NET AJAX:

Client-script functionality of the Microsoft AJAX Library, and any custom script that you want
to send to the browser. For more information, see ASP.NET AJAX and JavaScript.

27

Partial-page rendering, which enables regions on the page to be independently refreshed


without a postback. The ASP.NET AJAX UpdatePanel, UpdateProgress, and Timer controls
require a ScriptManager control to support partial-page rendering.

JavaScript proxy classes for Web services, which enable you to use client script to access
Web services by exposing Web services as strongly typed objects.

JavaScript classes to access ASP.NET authentication and profile application services.

Enabling Partial-Page Rendering


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, partial-page rendering is enabled by default 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 Errors
During partial-page rendering, you can handle errors by doing the following:

Set the AllowCustomErrorsRedirect property, which 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.

Using Type System Extensions


Microsoft AJAX Library adds type-system extensions to JavaScript that provide namespaces,
inheritance, interfaces, enumerations, reflection, and helper functions for strings and arrays. These
extensions provide functionality in client script that is like that of the .NET Framework. They enable

28

you to write ASP.NET 2.0 AJAX Extensions applications in a structured way that improves
maintainability, makes it easier to add features, and makes it easier to layer functionality. Adding a
ScriptManager control to an ASP.NET Web page automatically includes the type-system extensions
so that you can use the library in client script. For more information, see Extending JavaScript with
ASP.NET AJAX.

Registering Custom Script


Use the ScriptManager control to manage resources that you have created for controls that
participate in partial-page updates. Resources include scripts, styles, hidden fields, and arrays. The
Scripts collection of the ScriptManager control contains a ScriptReference object for each script that
is available to the browser. You can specify the scripts declaratively or programmatically.
The ScriptManager control also exposes registration methods that you can use to manage client
script and hidden fields programmatically. When you are registering script or hidden fields that
support partial-page updates, you must call registration methods of the ScriptManager control. (To
register scripts that are not needed for partial-page updates, you use methods of the
ClientScriptManager class.)
note
Any scripts on the page that are registered with the ScriptManager control and all event-handling
script must be inside the <form> element on the page. Otherwise the script will not be registered or
executed.
For a list of the ClientScriptManager controls registration methods, see Creating Custom Client
Script in ASP.NET AJAX and the ClientScriptManager class overview.

Registering Web Services


The ScriptManager control's Services collection contains a ServiceReference object for each Web
service that is registered with the ScriptManager control. The ASP.NET AJAX framework generates a
client proxy object for each ServiceReference object in the Services collection. The proxy classes
and their strongly typed members simplify using Web services from client script.
You can programmatically add ServiceReference objects to the Services collection to register Web
services at run time. For more information, see Web Services.

Using Authentication and Profile Services from Client Script


The Microsoft AJAX Library includes proxy classes for calling the ASP.NET 2.0 forms authentication
and profile application services directly from JavaScript. If you want to use a custom authentication
service, you can register it using the ScriptManager control. For more information, see ASP.NET
Application Services.

29

The ScriptManagerProxy Class


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. In cases where a ScriptManager control is already on the page
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.

Class Reference
Class

Description

ScriptManager

A server control that makes script resources available to the browser,


including the Microsoft AJAX Library and the functionality that enables
partial-page rendering.

ScriptManagerProxy A server control that enables nested components to add script and service
references if the page already contains a ScriptManager control.

See Also

ASP.NET Page Life Cycle Overview


ASP.NET AJAX and JavaScript
Partial-Page Rendering Overview
Web Services
ASP.NET Application Services
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

Timer Control Overview


Introduction
The Timer control performs postbacks at defined intervals. If you use the Timer control with an
UpdatePanel control, you can enable partial-page updates at a defined interval. You can also use the
Timer control to post the whole page.
This topic contains the following sections:

Scenarios
Background

30

Code Examples
Class Reference

Timer Control Scenarios


You use the Timer control when you want to do the following:

Periodically update the contents of one or more UpdatePanel controls without refreshing the
whole Web page.

Run code on the server every time that a Timer control causes a postback.
Synchronously post the whole Web page to the Web server at defined intervals.

Background
The Timer control is a server control that embeds a JavaScript component into the Web page. The
JavaScript component initiates the postback from the browser when the interval that is defined in
the Interval property has elapsed. You set the properties for the Timer control in code that runs on
the server and those properties are passed to the JavaScript component.
An instance of the ScriptManager class must be included in the Web page when you use the Timer
control.
When a postback was initiated by the Timer control, the Timer control raises the Tick event on the
server. You can create an event handler for the Tick event to perform actions when the page is
posted to the server.
Set the Interval property to specify how often postbacks will occur, and set the Enabled property to
turn the Timer on or off. The Interval property is defined in milliseconds and has a default value of
60,000 milliseconds, or 60 seconds.
note
Setting the Interval property of a Timer control to a small value can generate significant traffic to
the Web server. Use the Timer control to refresh the content only as often as necessary.
You can include more than one Timer control on a Web page if different UpdatePanel controls must
be updated at different intervals. Alternatively, a single instance of the Timer control can be the
trigger for more than one UpdatePanel control in a Web page.

Using a Timer Control Inside an UpdatePanel Control

31

When the Timer control is included inside an UpdatePanel control, the Timer control automatically
works as a trigger for the UpdatePanel control. You can override this behavior by setting the
ChildrenAsTriggers property of the UpdatePanel control to false.
For Timer controls inside an UpdatePanel control, the JavaScript timing component is re-created
only when each postback finishes. Therefore, the timed interval does not start until the page returns
from the postback. For instance, if the Interval property is set to 60,000 milliseconds (60 seconds)
but the postback takes 3 seconds to complete, the next postback will occur 63 seconds after the
previous postback.
The following example shows how to include a Timer control inside an UpdatePanel control.

<asp:ScriptManager runat="server" id="ScriptManager1" />


<asp:UpdatePanel runat="server" id="UpdatePanel1"
UpdateMode="Conditional">
<contenttemplate>
<asp:Timer id="Timer1" runat="server"
Interval="120000"
OnTick="Timer1_Tick">
</asp:Timer>
</contenttemplate>
</asp:UpdatePanel>

Using a Timer Control Outside an UpdatePanel Control


When the Timer control is outside an UpdatePanel control, you must explicitly define the Timer
control as a trigger for the UpdatePanel control to be updated.
If the Timer controls is outside an UpdatePanel control, the JavaScript timing component continues
to run as the postback is being processed. For example, if the Interval property is set to 60,000
milliseconds (60 seconds) and the postback takes 3 seconds to complete, the next postback will
occur 60 seconds after the previous postback. The user will see the refreshed content in the
UpdatePanel control for only 57 seconds.
You must set the Interval property to a value that enables one asynchronous postback to complete
before the next postback is initiated. If a new postback is initiated while an earlier postback is being
processed, the first postback is canceled.
The following example shows how to use the Timer control outside an UpdatePanel control.

<asp:ScriptManager runat="server" id="ScriptManager1" />


<asp:Timer ID="Timer1" runat="server" Interval="120000"
OnTick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1"
EventName="Tick" />
</Triggers>

32

<ContentTemplate>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>

Code Examples
The following example shows an UpdatePanel control that displays a randomly generated stock price
and the time that the stock price was generated. By default, the Timer control updates the content
in the UpdatePanel every 10 seconds. The user can decide to update the stock price every 10
seconds, every 60 seconds, or not at all. When the user chooses not to update the stock price, the
Enabled property is set to false.

cs
<%@ Page Language="C#" AutoEventWireup="true" %>
<!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 id="Head1" runat="server">
<title>Timer Example Page</title>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
OriginalTime.Text = DateTime.Now.ToLongTimeString();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
StockPrice.Text = GetStockPrice();
TimeOfPrice.Text = DateTime.Now.ToLongTimeString();
}
private string GetStockPrice()
{
double randomStockPrice = 50 + new Random().NextDouble();
return randomStockPrice.ToString("C");
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
Timer1.Enabled = true;
Timer1.Interval = 10000;
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
Timer1.Enabled = true;
Timer1.Interval = 60000;
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
Timer1.Enabled = false;
}
</script>
</head>

33

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server"
Interval="10000" />
<asp:UpdatePanel ID="StockPricePanel" runat="server"
UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>
<ContentTemplate>
Stock price is <asp:Label id="StockPrice" runat="server"></asp:Label><BR
/>
as of <asp:Label id="TimeOfPrice" runat="server"></asp:Label>
<br />
</ContentTemplate>
</asp:UpdatePanel>
<div>
<br />
Update stock price every:<br />
<asp:RadioButton ID="RadioButton1" AutoPostBack="true"
GroupName="TimerFrequency" runat="server" Text="10 seconds"
OnCheckedChanged="RadioButton1_CheckedChanged" /><br />
<asp:RadioButton ID="RadioButton2" AutoPostBack="true"
GroupName="TimerFrequency" runat="server" Text="60 seconds"
OnCheckedChanged="RadioButton2_CheckedChanged" /><br />
<asp:RadioButton ID="RadioButton3" AutoPostBack="true"
GroupName="TimerFrequency" runat="server" Text="Never"
OnCheckedChanged="RadioButton3_CheckedChanged" />
<br />
Page loaded at <asp:Label ID="OriginalTime" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

vb
<%@ Page Language="VB" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Timer Example Page</title>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
OriginalTime.Text = DateTime.Now.ToLongTimeString()
End Sub
Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)
StockPrice.Text = GetStockPrice()
TimeOfPrice.Text = DateTime.Now.ToLongTimeString()
End Sub
Private Function GetStockPrice() As String
Dim randomStockPrice As Double = 50 + New Random().NextDouble()
Return randomStockPrice.ToString("C")
End Function

34

Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal e As


System.EventArgs)
Timer1.Interval = 10000
Timer1.Enabled = True
End Sub
Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, ByVal e As
System.EventArgs)
Timer1.Interval = 60000
Timer1.Enabled = True
End Sub
Protected Sub RadioButton3_CheckedChanged(ByVal sender As Object, ByVal e As
System.EventArgs)
Timer1.Enabled = False
End Sub
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server"
Interval="10000" />
<asp:UpdatePanel ID="StockPricePanel" runat="server"
UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>
<ContentTemplate>
Stock price is <asp:Label id="StockPrice" runat="server"></asp:Label><BR
/>
as of <asp:Label id="TimeOfPrice" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<div>
<asp:RadioButton ID="RadioButton1" AutoPostBack="true"
GroupName="TimerFrequency" runat="server" Text="10 seconds"
OnCheckedChanged="RadioButton1_CheckedChanged" /><br />
<asp:RadioButton ID="RadioButton2" AutoPostBack="true"
GroupName="TimerFrequency" runat="server" Text="60 seconds"
OnCheckedChanged="RadioButton2_CheckedChanged" /><br />
<asp:RadioButton ID="RadioButton3" AutoPostBack="true"
GroupName="TimerFrequency" runat="server" Text="Never"
OnCheckedChanged="RadioButton3_CheckedChanged" /><br />
<br />
Page originally created at <asp:Label ID="OriginalTime"
runat="server"></asp:Label>
</div>
</form>
</body>
</html>

Tutorials
Introduction to the Timer Control
Using the Timer Control with Multiple UpdatePanel Controls

35

Class Reference
The key server classes for the Timer control are shown in the following table.
Timer

Performs asynchronous or synchronous Web page postbacks at a defined interval.

See Also
Partial-Page Rendering Overview
UpdatePanel Control Overview
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

Asynchronous Communication Layer Overview


Introduction
The Microsoft ASP.NET AJAX asynchronous communication layer enables a browser to call Web
service methods on the server by using ECMAScript (JavaScript). It exposes APIs that JavaScript
functions can use in any browser to call Web service methods on the server. These APIs use the
functionality for browser asynchronous behavior provided by the browser's XMLHTTP object. For
more information about the XMLHTTP object, see About Native XMLHTTP on the MSDN Web site.
The asynchronous communication layer provides a clear separation between the business and data
tiers on the server, and the presentation tier on the client. The browser has control of the
presentation tier and provides a rich and responsive user interface, and the server performs the
business and data tier tasks.
This topic contains the following information:
Asynchronous Communication Layer Features
Background
Code Examples
Class Reference
Additional Resources
What's New

36

Asynchronous Communication Layer Features


The asynchronous communication layer offers the following features:
Enables JavaScript code to perform asynchronous calls to the server.
Can invoke methods in Web services that are implemented as .asmx files.
Can invoke ASP.NET static page methods as if they were Web service methods.
Can be configured to enable and disable the ability to call Web services from ASP.NET AJAX
applications.
Supports a variety of serialization formats for passing data between the browser and the
server, including JavaScript Object Notation (JSON), string data, and XML data.
Makes Web service interactions easier by generating JavaScript proxies for Web services
that can be accessed from client script.
Provides extensibility for client executors that are used by the proxy objects. An executor is
a component that functions as an interface between a client Web request and the network
or other media. You can write your own executor that plugs into the asynchronous
communication layer. For more information, see XMLHttpExecutor Class.
Can be used with Medium trust.
Back to top

Background
The asynchronous communication layer provides an abstraction of low-level components in the
browser and on the server that enable you to perform client-server communication in JavaScript.

AJAX
Asynchronous JavaScript and XML (AJAX) enables you to create more interactive and more
responsive Web applications than those that rely exclusively on complete page postbacks. With
AJAX-style programming, the browser can exchange only the data it needs with the server, without
having to update the complete page.
AJAX relies on the following combination of technologies:
Asynchronous communication between the browser and server by using the XMLHTTP
object that is built into browsers.

37

A format for exchanging data between the browser and server. This format usually is XML,
but it can also be JSON (as in ASP.NET AJAX) or another format.
Data presentation in the browser by using XHTML, HTML, and CSS.
Client scripting that uses the browser document object model (DOM) and JavaScript to
create a responsive user interface (UI).

JSON
JavaScript Object Notation (JSON) is a lightweight format for representing objects and their state.
The asynchronous communication layer uses JSON as a serialization format instead of the SOAP
format more typically used with Web services. Using JSON simplifies client-server interaction,
because it eliminates the need for extensive client script to construct requests that use SOAP and
XML.
note
You do not have to understand the details of JSON format or serialization unless you have to extend
or customize system capabilities. For example, you might have to know JSON format if you want to
modify the way that ASP.NET 2.0 AJAX Extensions serializes specific custom types.

Calling Web Service Methods


ASP.NET 2.0 AJAX Extensions enables you to call ASP.NET Web services from the browser by using
client script. The page can call server-based methods without a postback and without refreshing the
whole page, because only data is transferred between the browser and the Web server. This
following code example shows how to expose a Web service method in an ASP.NET Web page.
Run View
This example is currently not available.

Making HTTP Requests


The previous example of calling a Web service method from script does not require detailed
knowledge of HTTP requests. For more advanced scenarios, the asynchronous communication layer
enables a JavaScript to make a request over the network to any HTTP end point by using the
Sys.Net.WebRequest class.
The following example shows how to use a WebRequest object to implement GET and POST Web
requests that connect to the specified URLs (HTTP end points).
Run View
This example is currently not available.
To run the example you need the following:

38

A ConnectingEndPoints.aspx test page. This page contains a button to run the script that
makes a GET request and then a POST request. The results are returned asynchronously by
the default Sys.Net.XmlHttpExecutor instance and are displayed in the page.
The GetTarget.htm and the PostTarget.aspx pages. These are the target pages for the GET
request and the POST request, respectively.
The supporting ConnectingEndPoints.js script. This script does the actual work of making
the requests, and it provides the handler function which receives the results of the request.

Client-Server Communication
The following illustration shows how the asynchronous communication layer communicates between
the client and the server.

Client-server communication
In physical terms, part of the asynchronous communication layer is on the client in the form of
downloaded scripts. The other part is on the server in the form of handlers and Web services.

Client Architecture
The client asynchronous communication layer consists of several JavaScript components. The
following illustration shows the client architecture of the asynchronous communication layer.

39

Client architecture
The client architecture contains two main groups: the communication group and the support group.

Communication Group
The communication group contains client script that performs Web services communication between
the client and the server. Note that Web request handling is intrinsically an asynchronous process.
The communication group is based on the browsers XMLHTTP object and on executor objects that
dispatch browser requests to the Web service.

Web Service Proxy Classes


In Microsoft ASP.NET AJAX, the asynchronous communication layer generates client-script proxy
classes automatically. You can then use the JavaScript proxy objects to make asynchronous
requests to the server from client script. There are two possible approaches to making a Web
service request:
Calling Web services by using the HTTP POST verb. A POST request has a body that
contains the data that the browser sends to the server. It does not have a size limitation.
Therefore, you can use a POST request when the size of the data exceeds the intrinsic size
limitation for a GET request. The client serializes the request into JSON format and sends it
as POST data to the server. The server deserializes the JSON data into .NET types and
makes the actual Web service call. During the response, the server serializes the return
values and passes them back to the client, which deserializes them into JavaScript objects
for processing.

40

Calling Web services by using the HTTP GET verb. This resembles the functionality of a
POST request, with the following differences:

The client uses a query string to send the parameters to the server.

A GET request can call only a Web service method that is configured by using the
[ScriptMethod(UseHttpGet = true)] attribute.

Data size is limited to the URL length allowed by the browser.


note
GET requests are not recommended for method calls that modify data on the
server or that expose critical information. In GET requests, the message is encoded
by the browser into the URL and is therefore an easier target for tampering. For
both GET and POST requests, you should follow security guidelines to protect
sensitive data.

Page Method Proxy Classes


Page methods provide the scripting infrastructure for client script to call a static method in an
ASP.NET page (an .aspx page, master page, or .ascx control) as if it were a Web service method.

Support Group
The support group is responsible for handling proxy classes and the serialization required for clientserver communication.

Authentication Proxy Class


The authentication proxy class is generated by the server authentication service. It enables the user
to log in or log out through JavaScript in the browser without making a round trip to the server.

Profile Proxy Class


The profile proxy class is generated by the server profile service. It makes the current user's profile
information available to the client through JavaScript without making round trips to the server. It
also enables saving modified profile information to the server by using script.

JSON Serialization

41

The client JSON serialization component serializes JavaScript objects into JSON format.
Deserialization is available by using the JavaScript eval function.
Although JSON is the default serialization format, individual methods in Web services and in
ASP.NET Web pages can return alternative formats such as XML. The serialization format of a
method can be specified with attributes. For example, the [ScriptMethod(ResponseFormat.Xml)]
attribute causes a Web service method to return data in a browser-specific XMLDocument type. For
more information, see XML DOM Properties in the MSDN Library and the ScriptMethodAttribute class
overview.

Server Architecture
The server asynchronous communication layer consists of several components. The following
illustration shows the server architecture of the asynchronous communication layer.

Server architecture
The server asynchronous communication layer includes two main groups: a communication group
and a support group.

Communication Group
The server communication group is the high-level interface between the server and the client. It
contains the server communication components that correspond to similar components on the
client.

Web Services
In the Web Services component, the server performs all the required processing and returns an
appropriate response to the client.

Page Methods
The page-methods component enables a method in an ASP.NET page (an .aspx page, master page,
or .ascx control) to be called as if it were a Web service method.

42

Support Group
Components for the support group handle additional tasks such as serialization and application
services that are required for client-server data exchange.

JSON Serialization
The server JSON serialization component enables customizable serialization and deserialization of
common .NET types to and from JSON format.

XML Serialization
The asynchronous communication layer supports returning XML types from a Web service. If a Web
method returns an XmlDocument object, as specified by the server attribute
[ScriptMethod(ResponseFormat.Xml)], the callback function receives the return value as a
browser-specific XmlDocument type. For more information, see XMLDocument Property in the MSDN
Library.

Authentication Service
The authentication service generates an authentication proxy class and makes it available to client
script. This enables the user to log in or log out through JavaScript in the client.

Profile Service
The profile service generates a profile proxy class, which can be used in client script to get and set
profile properties for the user identity associated with the current request. The profile service works
for for authenticated users and for anonymous users when the anonymous identification feature is
enabled.
Back to top

Code Examples
Calling Web Services from Client Script
Exposing Web Services to Client Script
Using Forms Authentication
Using Profile Information
Back to top

43

Class Reference

Client Types
Name

Description

WebServiceProxy Class Enables calling a method of a specified Web service asynchronously.


WebRequest Class

Models the information needed by the asynchronous client-server


communication infrastructure to make an HTTP request. This class is
used by other asynchronous client-server communication classes.

WebRequestExecutor

Provides the functionality for interfacing with the network to perform

Class -

Web requests.

WebRequestManager

Manages the flow of network requests from the WebRequest class to

Class

the XMLHttpExecutor class that is responsible for making the actual


network requests.

WebServiceError Class

Handles errors for the Sys.Net namespace classes.

XMLHttpExecutor Class Makes asynchronous network requests using the browser's XMLHTTP
support.
JavaScriptSerializer

Provides serialization and deserialization functionality.

Class
AuthenticationService

Provides the client proxy class for the authentication service.

Class
ProfileGroup Class

Defines a profile group.

ProfileService Class

Provides the client proxy class for the profile service.

Server Types
Name

Description

ScriptingAuthenticationServiceSection Represents the configuration section for authentication


service settings.
ScriptingProfileServiceSection

Represents the configuration section for profile service


settings.

JavaScriptConverter

Provides an abstract base class for a custom type


converter.

JavaScriptSerializer

Provides serialization and deserialization functionality.

JavaScriptTypeResolver

Provides an abstract base class for implementing a

44

custom type resolver.


ScriptIgnoreAttribute

Specifies that a public property or public field will be


ignored by the JavaScriptSerializer when serializing or
deserializing an instance of a class.

SimpleTypeResolver

Provides a type resolver for managed types.

GenerateScriptTypeAttribute

Specifies that the server type must be generated in the


proxy object.

ResponseFormat

Specifies how the Web method return type is serialized.

ScriptMethodAttribute

Specifies which HTTP verb is used to invoke a method,


and the format of the response.

ScriptServiceAttribute

Indicates to the asynchronous communication layer that


a Web service can be invoked from script.

AuthenticationServiceManager

Configures the location of the authentication service.

ProfileServiceManager

Configures the location of the profile service.

Back to top

Additional Resources
About Native XMLHTTP article on the MSDN Web site
http://www.json.org Web site
Back to top

See Also

Exposing Web Services to Client Script


Using Profile Information
Using Forms Authentication
Configuring ASP.NET AJAX
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

Localizing Resources for Component Libraries Overview


Introduction

45

Localization is the process of customizing your application for a specific language and culture.
Microsoft ASP.NET AJAX supports the following localization models for working with client script:

The .NET Framework resources model, with expanded support for localized resources that
are associated with your ECMAScript (JavaScript) components. In this model, you embed
script files and localized script resources in a hub-and-spoke organization of assemblies
(that is, you use satellite assemblies). You can then selectively use these embedded client
scripts and resources for specific languages and regions. This model enables a single code
base to support multiple cultures.

Static (standalone) JavaScript files on disk. In this model, localized files are grouped in a
single directory as .js files instead of embedded in an assembly.

Updating scripts and script resources that are embedded in an assembly by using static
JavaScript files. This model enables you to provide additional localization support for
embedded scripts and for embedded resources without requiring any changes to the
original assembly.
This topic contains the following information:

Scenarios
Background
Localizing Client Scripts and Script Resources in Assemblies
Localizing Static Script Files and Their Resources
Using ScriptManager to Manage Scripts in a Central Location
Code Examples
Class Reference

Scenarios
ASP.NET AJAX helps client localization for both page developers and component developers. Page
developers will typically localize the following:

Exception messages that are generated from ASP.NET AJAX or component libraries, based
on the browsers language setting.

46

UI for controls, such as strings for the Text property of a Button control.
Values for public properties of ASP.NET AJAX server controls.
Values for properties of client script objects and components, such as non-visual
components, behaviors, and controls.
Component developers will typically use localization features for the following:

Localizing resources that are referenced in code in JavaScript libraries (.js files). The
localized resources can be deployed in separate installations, without rebuilding the main
assembly or the script library.

Exposing localizable properties on server controls that are mapped to properties of client
objects.

Background
Localization is the process of customizing your application for a specific language and culture.
ASP.NET AJAX builds on the ASP.NET 2.0 localization model and provides additional support for
localized script files that are embedded in an assembly or are static .js files on disk.
If you are not familiar with the ASP.NET localization model, you can find information about it in the
following topics:

Localizing ASP.NET Web Pages Using Resources


How to: Create Resource Files for ASP.NET Web Sites
Resource File Generator (Resgen.exe)

Localizing Client Script Files and Script Resources in Assemblies


ASP.NET AJAX takes advantage of the .NET Framework resources model for localization. This model
uses a hub-and-spoke arrangement to package and deploy localized resources that can be
incrementally updated. The hub is the main assembly that contains the non-localized executable
code. It includes both .NET Framework server code and any JavaScript code in .js files that are
embedded as a resource in the assembly.
The main assembly can also contain the resources for a single culture, which is referred to as the
neutral or default culture. The neutral culture is the fallback culture for the applicationthat is, the
culture settings that are used if no other culture is specified.

47

Localized resources for a culture are typically created as name/value pairs in .resx files. (These
.resx files can also be compiled into .resources files.) The name provides a way to access the
information in code, and the value is the localized (translated) term, image, or other element for
that name. When an assembly is built, a type is generated for the .resx file in which the names are
exposed as fields that provide programmatic access to the values. (You specify the name of this
generated type as part of the assembly properties, as described later.)
In the hub-and-spoke model, each spoke connects to a satellite assembly that contains the
resources for a single culture. The satellite assembly does not contain any code executed by the
server. It contains only the generated type that provides programmatic access to the resource
values for that culture.
This model offers the following features:

You can add resources for new cultures by deploying new satellite assemblies after you
have already deployed an ASP.NET AJAX assembly. Developing culture-specific resources
can require extra time. This model therefore enables you to release your main application
first, and deliver additional culture-specific resources later.

You can update an application's satellite assemblies without recompiling your main
assembly.

An application has to load only the satellite assembly for a particular culture, instead of
unloading and reloading the main assembly. This can significantly reduce the use of system
resources.
For information about how to create resource files for ASP.NET, see How to: Create Resource Files
for ASP.NET Web Sites and Localizing ASP.NET Web Pages Using Resources.
For information about using the .NET Framework resource-file generator (Resgen.exe) tool, see
Resource File Generator (Resgen.exe). This tool converts .resx or .txt files to binary .resources
files that can be linked into assemblies.

Organizing Localized Main and Satellite Assemblies


You can use the hub-and-spoke model when you want to localize an application that includes
JavaScript (.js) files. In general, you organize the assembly as you would any ASP.NET application
that is localized.
To manage the JavaScript files for an ASP.NET AJAX application, you write JavaScript code so that it
does not hard-code strings or other elements that should be localized. Instead, in any place where
the JavaScript code must use localized values, you get a field from the type that is generated out of
the resource file.

48

The main assembly typically includes the following elements:

The JavaScript files that perform the application tasks, and that are written to use localized
resources instead of hard-coded ones. The assembly can optionally include debug versions
of these JavaScript files.

Optionally, the resources (.resx or .resources file) for a single neutral culture, which acts as
the fallback culture for the application.

Optionally, any debug versions of neutral-culture resources. The debug version of a


resource file includes any extra name/value pairs that are required for the debug versions
of the JavaScript files.
A satellite assembly typically includes localized resources for a single culture for the ASP.NET
application. (No satellite assembly is required for the fallback culture.) The resources for a single
culture are created in a separate resource file (.resx or .resources file) and then compiled into a
single satellite assembly.
note
ASP.NET AJAX enables you to create your own custom culture and your own culture name. However,
typically culture names are based on an ISO language code that consists of two letters for a
language and two uppercase letters for a country or region. Examples include es-MX
(Spanish, Mexico), es-CO (Spanish, Columbia), and fr-CA (French, Canada). For a complete list of
culture names, see the CultureInfo class overview.

Names for Localized Embedded Script Files


The following naming convention is recommended for localized script files that are embedded as
resources:

scriptname_noextension.[debug].[UI culture identifier].resources


The debug version of a file name includes ".debug" in the name. The release version does not.
The following table shows examples of this naming convention. These examples show both a release
and debug version of an embedded script file followed by the associated release and debug versions
of resources for those script files.
Sample.js
A release version of a neutral-culture script file, which is embedded in the main assembly.
Sample.debug.js
A debug version of a neutral-culture script file, which is also embedded in the main
assembly.

49

Sample.fr-FR.resources
A release version of resources that are associated with the script file Sample.js, localized for
a specific UI culture. These resources become part of the satellite assembly.
Sample.debug.fr-FR.resources
Debug-specific resources associated with the script file Sample.debug.js, localized for a
specific UI culture. These resources become part of the satellite assembly that also includes
the Sample.fr-FR.resources file.
This naming convention is not strictly required for script files that are embedded in assemblies or for
resource files. This is because the mapping between the type generated for the resource and the
resource name is accomplished by using an assembly attribute.

Localizing Debug Script Resources


If you are working in debug mode, at run time ASP.NET AJAX combines the release version of
resources for script files with any additional debug resources. It then sends the resulting
combination to the browser. Therefore, when you create resource files for debug versions of scripts,
you have to define only the name/value pairs that are not already included in the release script
resource files. By convention, debug versions of scripts and of script resources use the same name
as their release counterpart but include ".debug" after the script file name.

Specifying Assembly Attributes for Localized Scripts and Localized


Resources Associated with Scripts
To specify how resource files are managed when an assembly is built, you include attributes in the
AssemblyInfo file (AssemblyInfo.vb or AssemblyInfo.cs file).
note
In Visual Studio, the AssemblyInfo.vb file is in the My Project node of Solution Explorer. If you do
not see any files in the My Project node, in the Project menu, click Show All Files. The
AssemblyInfo.cs file is in the Properties node of Solution Explorer.
In ASP.NET, you mark resources for the application by using the WebResourceAttribute class. To
embed JavaScript files in an assembly, you use this attribute to specify the .js files as a Web
resource.
To include resource files for the embedded JavaScript files, you use the ScriptResourceAttribute
class that is provided by ASP.NET AJAX. This attribute identifies the files specifically as resources for
the JavaScript files.
The following example shows how to use assembly attributes to identify embedded scripts and their
associated script resources.

50

' Indicates that neutral fallback resources are retrieved from


' the main assembly named MainAssembly.
<assembly: NeutralResourcesLanguageAttribute("en-US",
UltimateResourceFallbackLocation.MainAssembly)>
' Defines embedded scripts as Web resources.
<assembly:WebResource("Sample.js", "text/javascript")>
<assembly:WebResource("Sample.debug.js", "text/javascript")>
' Defines the script resources for the scripts and their types.
<assembly:ScriptResource("Sample.js", "Sample.resources",
"Sample.Res")>
<assembly:ScriptResource("Sample.debug.js", "Sample.debug.resources",
"Sample.Res")>
// Indicates that neutral fallback resources are retrieved from
// the main assembly named MainAssembly.
[assembly: NeutralResourcesLanguageAttribute("en-US",
UltimateResourceFallbackLocation.MainAssembly)]
// Defines embedded scripts as Web resources.
[assembly:WebResource("Sample.js", "text/javascript")]
[assembly:WebResource("Sample.debug.js", "text/javascript")]
// Defines the script resources for the scripts and their types.
[assembly:ScriptResource("Sample.js", "Sample.resources",
"Sample.Res")]
[assembly:ScriptResource("Sample.debug.js", "Sample.debug.resources",
"Sample.Res")]
In this example, a main assembly named MainAssembly contains an embedded release version of a
client script file that is named Sample.js. The assembly also contains the corresponding debug
version named Sample.debug.js. The .js files are identified as resources by the
WebResourceAttribute attribute.
The NeutralResourcesLanguageAttribute assembly attribute is used to specify the main assembly as
the fallback culture. For more information, see Neutral Resources Languages for Localization and the
NeutralResourcesLanguageAttribute class overview.
The resources used by the script files are defined by using the ScriptResourceAttribute attribute.
The Sample.resources and Sample.debug.resources files contain resource values for the Sample.js
and Sample.debug.js files, respectively.
A type named Sample.Res is generated for both the release and the debug version of the script
resources. This is the type that the JavaScript code should use to access localized values. For both
release mode and debug mode, the build process creates only a single type. In debug mode the
resources for the release version are combined with the additional resources for the debug version.
For more information about how to create assembly-information files and the assembly metadata
that is required for versioned assemblies, see How to: Create Versioned Assemblies for Precompiled
Web Sites.

Localizing Static Script Files and Their Resources

51

You can organize a script library as localized static script files (.js files) on disk instead embedding
the script files in assemblies. Page developers can reference the script files through the
ScriptReferenceCollection class.
In the static script file model, there are no separate .resx or .resources files that can be
automatically managed as resources for the JavaScript files. Instead, there are only .js files, one for
every UI culture and locale combination. In effect, each .js file represents a locale-specific version of
the complete JavaScript code. A typical way to manage localized script files in this model is to use
the same JavaScript logic in each .js file. As in the assembly-embedded model, the JavaScript code
invokes a type to retrieve localized resource values. The difference is that you must supply the type
that contains the localized valuesit is not generated for you. For example, the .js for each locale
can include both the application code and a class that defines the fields that hold localized values. In
each .js file, this class would contain values in a different language.
note
In the static script file model, the application JavaScript code in .js files can get out of sync with the
code in an embedded JavaScript file. This is because each script file includes a copy of the code. To
avoid version control issues with duplicated code, you can maintain a single copy of the JavaScript
source files and create localized resource types in separate files. You can then generate the final
combined files during your application's build process.
Localized static script files are mapped to their UI culture by including the UI culture name as part
of the file name, as with embedded resources in an assembly. For example, an embedded client
script file that is culturally neutral for French would be named Sample.fr.js and a culture-specific
JavaScript resource for French (Canada) would be named Sample.fr-CA.js.

Localized Debug Scripts in the Static Script File Model


In the static script file model, localized resources that a script refers to are typically defined as a
type in a single .js file. A debug version of a script file is organized in the same way, with both
localized release resources and additional debug resources defined as a type in a single file. Debug
versions of scripts use the same name as the corresponding release version, but include ".debug"
after the name.

Using ScriptManager to Manage Scripts


You can use the ScriptManager control to manage static scripts that are located in a central
directory on disk. To do so, put all versions of the script files in one folder, including release and
debug versions of all localized files. The following example shows the layout of a directory structure
for a static script file library:
SampleNamespace/
1.0.0.0/

52

Sample.js
Sample.debug.js
Sample.de-DE.js
Sample.debug.de-DE.js
Sample.fr-FR.js
Sample.debug.fr-FR.js
In this example, all the script files are in a folder that is named by using the script library version
(1.0.0.0). This version-specific folder is in turn in a folder that is named after the library's
namespace. Organizing a script library within folders by namespace and version can provide some
version control for your library and it can help you avoid script-name collisions between libraries. It
also enables consumers of your library to identify what library and library version the files belong to.

Understanding the Role of the ScriptManager Control in Localization


The ScriptManager control provides the following functionality for using localized scripts and script
resources:

Enables you to define which UI cultures are supported, which includes custom UI cultures.
Interprets the culture-specific assembly attribute and automatically detects the UI culture
of the browser (if any), and then reads the localized or fallback scripts and resources from
the assembly. In debug mode, it tries to load a script resource that contains both the
appropriate UI culture name and the string ".debug" in the file name, such as
Sample.debug.fr-FR.resources.

Generates URLs that point to the appropriate scripts and to their localized resources. For
added security, it encrypts the URLs.

Determines whether a script or script resource will be compressed, based on a parameter in


the generated URL.

Adds a timestamp to the assembly that contains embedded scripts so that the browser does
not indefinitely cache the scripts.
For more information, see the ScriptManager class overview.

53

The following example shows part of a Web page that uses the ScriptManager control to register a
client control that is located in an assembly. The embedded script is registered by using the
Assembly and Name properties.

<%@ Register TagPrefix="Samples" Namespace="DemoControls"


Assembly=" SampleAssembly" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ScriptReference</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Assembly="SampleAssembly"
Name="DemoControls.SampleControl.js" />
</Scripts>
</asp:ScriptManager>
<!-- Additional markup here. -->
</div>
</form>
</body>

Code Examples
The following sections include code examples that show how to work with JavaScript files and
resources.

How-to and Walkthrough Topics


Embedding a JavaScript File as a Resource in an Assembly
Embedding Localized Resources for a JavaScript File
Adding Localized Resources to a JavaScript File

Class Reference
The following table lists the key classes that are used for localizing component libraries.
ScriptManager
Manages ASP.NET 2.0 AJAX Extensions components, partial-page rendering, client requests,
and server responses on ASP.NET server pages.

54

ScriptReference
Provides APIs for registering JavaScript files for use in a Web page, either files that are
embedded in an assembly or that are on disk.
ScriptReferenceCollection
Provides access to ScriptReference objects that represent client script files.

See Also

ASP.NET Web Page Resources Overview


Creating Custom ASP.NET AJAX Non-Visual Client Components
How to: Create Resource Files for ASP.NET Web Sites
How to: Create Versioned Assemblies for Precompiled Web Sites
Dynamically Assigning ASP.NET AJAX Script References
Localizing ASP.NET Web Pages Using Resources
Resource File Generator (Resgen.exe)
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

ASP.NET AJAX Client Life-Cycle Events


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

55

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

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

VB
Sys.Application.add_init(MyInit);
function MyInit(sender) {
}
Sys.Appplication.remove_init(MyInit);
note
This example shows just the syntax of the add_eventname and remove_eventname methods.
Details about what you can do with specific events are provided later in this topic.

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

56

pageUnload. The following example shows how to add a handler for the load event of the
Application object by using this approach.

CS
function pageLoad(sender, args) {
}

VB
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:

The Sys.UI.DomEvent.addHandler method or the shortcut $addHandler.


The Sys.UI.DomEvent.clearHandlers method or the shortcut $clearHandlers.
The Sys.UI.DomEvent.removeHandler method or the shortcut $removeHandler.
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 ASP.NET-enabled pages. The order in which the events are raised is described
later in this topic.

Event

Description

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.

57

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.

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.

propertyChanged Potentially raised when a property of a component changes. The Application


Event

object inherits this event from the Component class. 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.

disposing Event

Raised when the Application instance is disposed. The Application object


inherits this event from the Component class.

initializeRequest

Raised before an asynchronous request starts. You can use this event to

Event

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.

beginRequest

Raised before an asynchronous postback starts and the postback is sent to

Event

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

58

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

Raised after the response from the server to an asynchronous postback is

Event

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.

pageLoaded

Raised after all content on the page is refreshed, as a result of either a

Event

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.

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 Example


The following example shows the client events that are raised on a page that includes two
UpdatePanel controls, one nested inside the other. You will notice a difference between clicking the
button in the parent panel and clicking the button in the nested panel. The button in the parent
panel causes the parent panel to be updated and the nested panel to be deleted and recreated. The
button in the nested panel causes just the nested panel to be updated.
Run View

Event Order for Common Scenarios

59

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

60

A response from the server is returned successfully.


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 PageRequestManager Events.
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.

61

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:

62

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

See Also

ASP.NET Page Life Cycle Overview


Defining Custom Component Properties and Raising PropertyChanged Events
Working with PageRequestManager Events
Creating Custom Client Events
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

ASP.NET AJAX Debugging and Tracing Overview


Introduction
Microsoft ASP.NET AJAX applications contain a mix of server code and client code. The browser can
also request additional data asynchronously. This can make debugging AJAX-enabled Web
applications challenging. This overview discusses some techniques and tools that can help
you debug your code more easily.
note
With the exception of Visual Studio and Internet Explorer, the programs mentioned in this topic are
third-party tools and are not supported by Microsoft. Please see the tool's Web site for licensing and
support information.
This topic contains:

63

Scenarios
Background
Class Reference

Scenarios
You can use the following approaches to debug an ASP.NET AJAX application at different stages of
development:

Enable debugging in the configuration file.


Use tracing on the server.
Use the methods of the Sys.Debug class to set breakpoints and handle trace output.
Enable debugging in your browser.
Attach the Visual Studio debugger to your Internet Explorer instance, or use external tools
to debug in other browsers.

Use external tools to capture HTTP traffic.


Back to top

Background
The ASP.NET AJAX architecture provides a model for release and debug modes. Release mode
provides error checking and exception handling optimized for performance, with minimized script
size. Debug mode provides more robust debugging features, such as type and argument checking.
If you create debug versions of your client scripts or script resources, 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.
A debug helper class, Sys.Debug, provides methods for displaying objects in readable form at the
end of a Web page. It also shows trace messages, enables you to use assertions, and lets you break
into the debugger. An extended Error Object object API provides helpful exception details with
support for release and debug modes.
The following sections provide detail about the techniques and tools that you can use for debugging
and tracing.

64

Configuring the Application for Debugging


To enable debugging, add a compilation element to the site's root Web.config file, and then set its
debug attribute to true. For more information, see compilation Element (ASP.NET Settings Schema).
The following example shows a section from a Web.config file that has the debug attribute set.

<configuration>
<system.web>
<compilation debug="true">
<!-- etc. -->
</compilation>
</system.web>
<configuration>
When debugging is enabled, ASP.NET AJAX uses a debug version of the client libraries.

Setting the Application from Debug to Release Mode for Deployment


When you deploy a release version of an AJAX-enabled ASP.NET application, make sure that it is set
to release mode. This makes sure that ASP.NET uses the performance-optimized release version of
the ASP.NET AJAX libraries. If you have created debug and release versions of your custom scripts
and script resources, ASP.NET also uses the release versions. To set the application to release mode,
do the following:

In the Web.config file, if the compilation element contains a debug attribute, make sure
that the debug attribute is set to false.

Make sure that any Web page that contains a ScriptManager control has its ScriptMode
property set to Release.
The debug attribute of the @ Page directive does not affect ASP.NET AJAX applications. The
ScriptManager control uses only the settings in the Web.config file and in its
IsDebuggingEnabled and ScriptMode properties to determine whether to render debug scripts.

Tracing on the Server


If you are using tracing on the server to debug Web pages that have partial-page rendering
enabled, you should use the trace viewer (Trace.axd) to display trace output. You can append trace
output to the end of the page, and it is displayed the first time the page is rendered. However, the
trace display is not updated as a result of asynchronous postbacks, because only the contents of
UpdatePanel controls that have to be refreshed will change. For more information about how to use
the trace viewer, see ASP.NET Tracing.
note

65

Partial-page rendering is enabled when the page contains a ScriptManager control with its
EnablePartialRendering property set to true. The page must also contain one or more UpdatePanel
controls.

Debug Helper Class


Microsoft AJAX Library provides the Sys.Debug class for debugging client applications. By calling
methods of the Sys.Debug class, you can display objects in readable form at the end of the page,
show trace messages, use assertions, and break into the debugger.
If you are using Visual Studio and Internet Explorer, you can attach the Visual Studio debugger to
the browser and view debugger trace messages in the Output window. If you are not using Visual
Studio, you can view debugger trace messages in Internet Explorer by creating a textarea element
on the page and setting its ID to TraceConsole. In Mozilla Firefox, you can view debugger trace
messages by using tools that are available as extensions. The Apple Safari and Opera browsers
display trace messages in their respective debugging consoles.
The following table lists the methods of the Sys.Debug class.
Sys.Debug.assert(condition, message, displayCaller)
Checks for a condition, and if the condition is false, displays a message and prompts the
user to break into the debugger.
Sys.Debug.clearTrace()
Clears all trace messages from the TraceConsoletextarea element.
Sys.Debug.traceDump(object, name)
Dumps an object to the debugger console and to the TraceConsoletextarea element, if
available.
Sys.Debug.fail(message)
Displays a message in the debugger's output window and breaks into the debugger.
Sys.Debug.trace(text)
Appends a text line to the debugger console and to the TraceConsoletextarea element, if
available.
The following example shows how to call methods of the Sys.Debug class:
Run View

Configuring Internet Explorer for Debugging


By default, Internet Explorer ignores problems it encounters in JavaScript. You can enable
debugging by using the following procedure.

66

To enable debugging in Internet Explorer


1.

In the Tools menu, click Internet Options.

2.

In the Advanced tab, clear the Disable Script Debugging (Internet Explorer) check
box and the Disable Script Debugging (Other) check box.

3.

Select the Display a notification about every script error check box.

4.

To turn off "friendly" error messages, clear the Show friendly HTTP error messages
check box.
If "friendly" error message are enabled and if an HTTP 500 error response from the server is less
than 513 bytes long, Internet Explorer masks the content. In place of the error information,
Internet Explorer displays a message that is meant for end users, not developers.

Attaching the Visual Studio Debugger to Internet Explorer

67

To debug client script, you must attach a debugger to Internet Explorer. In Visual Studio, if you start
your application for debugging (by pressing F5 or using the Start Debugging command in the
Debug menu), the debugger is attached automatically.
You can also attach the Visual Studio debugger to Internet Explorer when the application is already
running. To do so, in the Debug menu, click Attach to Process.... In the Attach to Process
dialog box, select the instance of Internet Explorer (iexplore.exe) that you want to attach the
debugger to.
note
If Internet Explorer is configured for debugging, the Type column for the relevant instance of
Internet Explorer displays Script, x86. If you see only x86 in the Type column, make sure that
Internet Explorer is configured for debugging.
If Internet Explorer encounters a script error and is configured for script debugging, but it is not
currently attached to a debugger, the browser prompts you to select a debugger. You can either
continue without debugging or attach a debugger and step through the code.

Internet Explorer Known Debugging Issues and Workarounds


When you debug ASP.NET AJAX applications that use Internet Explorer, be aware of the following
issues and workarounds:

After the Visual Studio debugger is attached to Internet Explorer, you can see a list of the
scripts that are being debugged in the Visual Studio Script Explorer window. (To display
this window, in the Debug menu, click Windows, and then click Script Explorer). The
ASP.NET AJAX client library will appear as a resource starting with
ScriptResource.axd?..., which the server generates dynamically from the ASP.NET
AJAX assembly. A known bug in Visual Studio might prevent you from opening the file. If
Visual Studio displays an error message to that effect, or if it ignores clicks on the file
name, close all script files that are open. You can then open the page and select the script
files that you want to debug.

You cannot set breakpoints in JavaScript code inside script elements in an ASP.NET page
until after the debugger has stepped into JavaScript code on that page. To work around this
issue, set the breakpoint on the function that the call comes from, and step into the code
on the ASP.NET Web page. After the debugger has stopped on a line of JavaScript code in
the page, you can set breakpoints as usual. Another way to have the debugger recognize
scripts in an ASP.NET page is to create a method in the ASP.NET page file that calls the
Sys.Debug.fail method. When you call this method, the debugger will stop on the call to
Sys.Debug.fail and let you set breakpoints elsewhere. A third alternative is to put all your
custom code in external JavaScript files.

68

Visual Studio enables you to set breakpoints on the first line of a regular JavaScript
function, but not on the first line of anonymous methods, which ASP.NET AJAX uses. If an
anonymous method contains only one line of code, or if you must set a breakpoint on the
first line of an anonymous method, insert a dummy line of code. You can then set the
breakpoint on the second line of the method.

Capturing HTTP Traffic


When you develop Web applications, it is often useful to monitor the HTTP traffic between the server
and the client. A tool that can perform this task is Fiddler, which you can get from the Fiddler
PowerToy page on the MSDN Web site. Fiddler runs as a proxy that logs all HTTP traffic. It supports
Internet Explorer and other browsers. By using Fiddler, you can examine each request and
response, which includes headers, cookies, and message contents.

Debugging in Mozilla Firefox


Mozilla Firefox is not integrated with the Visual Studio debugger. As a result, you cannot use the
Visual Studio debugger to step through client code that is running in Firefox. However, Firefox
supports some debugging functionality, such as a JavaScript console. You can also install the
following extensions available from Mozilla that can enhance your debugging capabilities:

Fire B ug enables you to step through client script and examine HTML DOM elements. It
also provides a script console, a command line, and other tools.

The JavaScript Debugger (also known as "Venkman") provides a JavaScript debugging


environment that includes a source-code browser and other features.

The Web Developer extension enables you to inspect the DOM and CSS styles.
Fiddler also works with Firefox. However, you must configure Firefox to route HTTP requests through
the proxy running on port 8888 on the local computer. For more information, see the "Configuring
Clients" page on the Fiddler Web site.
Back to top

Class Reference
Debug Class
Provides methods that define breakpoints and handle trace output.

See Also

69

Overview
ASP.NET AJAX Roadmap
Localizing Resources for Component Libraries Overview
Back to top
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.

70

You might also like