Professional Documents
Culture Documents
The following illustration shows the functionality that is included in the client-script libraries and
server components.
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.
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.
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:
See Also
Installing ASP.NET AJAX
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.
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
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.
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
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.
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.
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.
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
10
Class Reference
The following table lists the key server classes for partial-page rendering.
Class
Description
UpdatePanel
ScriptManager
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
Class
See Also
UpdatePanel Control Overview
PageRequestManager Class Overview
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.
11
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.
13
postback that originates from anywhere on the page. This includes asynchronous
postbacks from
controls that are inside other UpdatePanel controls, and postbacks from controls
14
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.
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.
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.
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
ScriptManagerProxy
18
Additional Topics
ASP.NET Page Life Cycle Overview
See Also
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.
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.
21
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.
Code Examples
The following sections include code examples for creating and using UpdateProgress controls.
Class Reference
The following table lists the key classes for working with the UpdateProgress class.
Class
Description
UpdateProgress
UpdatePanel
ScriptManager
22
the server and exposes events and methods for custom client scripting.
Additional Topics
ASP.NET Page Life Cycle Overview
See Also
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.
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
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
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
Class
BeginRequestEventArgs
Class
PageLoadingEventArgs
Provides event data for the pageLoading event, which is raised after
Class
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
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
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.
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.
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.
29
Class Reference
Class
Description
ScriptManager
ScriptManagerProxy A server control that enables nested components to add script and service
references if the page already contains a ScriptManager control.
See Also
Scenarios
Background
30
Code Examples
Class Reference
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.
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.
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
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
See Also
Partial-Page Rendering Overview
UpdatePanel Control Overview
Copyright 2005 - 2007 Microsoft Corporation. All rights reserved.
36
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.
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.
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.
Support Group
The support group is responsible for handling proxy classes and the serialization required for clientserver communication.
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
WebRequestExecutor
Class -
Web requests.
WebRequestManager
Class
WebServiceError Class
XMLHttpExecutor Class Makes asynchronous network requests using the browser's XMLHTTP
support.
JavaScriptSerializer
Class
AuthenticationService
Class
ProfileGroup Class
ProfileService Class
Server Types
Name
Description
JavaScriptConverter
JavaScriptSerializer
JavaScriptTypeResolver
44
SimpleTypeResolver
GenerateScriptTypeAttribute
ResponseFormat
ScriptMethodAttribute
ScriptServiceAttribute
AuthenticationServiceManager
ProfileServiceManager
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
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:
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.
48
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.
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.
50
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.
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.
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.
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.
Code Examples
The following sections include code examples that show how to work with JavaScript files and
resources.
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
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.
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.
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) {
}
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.
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
initializeRequest
Raised before an asynchronous request starts. You can use this event to
Event
beginRequest
Event
58
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
Event
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.
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.
2.
3.
4.
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.
60
The button inside the UpdatePanel is clicked, which initiates an asynchronous postback.
2.
3.
4.
5.
6.
7.
8.
9.
The page contains a ScriptManager control and the control's SupportsPartialRendering and
EnablePartialRendering property are both true.
61
2.
3.
4.
5.
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.
10.
11.
12.
13.
14.
62
The page contains a ScriptManager control and the control's SupportsPartialRendering and
EnablePartialRendering property are both true.
2.
3.
4.
See Also
63
Scenarios
Background
Class Reference
Scenarios
You can use the following approaches to debug an ASP.NET AJAX application at different stages of
development:
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
<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.
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.
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.
66
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.
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.
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.
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 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