Pages

Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Monday, October 13, 2008

ASP.NET AJAX Overview

ASP.NET AJAX
Introduction

Microsoft ASP.NET AJAX documentation includes overviews, tutorials, and API reference topics. We suggest the following progression of documentation to help you to get started.
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
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 AJAX-like 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 client-script 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.
Sample ASP.NET AJAX Application
Introduction

This tutorial creates a basic sample application that uses features of Microsoft ASP.NET AJAX. You can read more about what ASP.NET AJAX is, what technical issues it is designed to solve, and what its important components are in the following introductory ASP.NET AJAX documents:

*

Overview
*

ASP.NET AJAX Roadmap

In this tutorial you will build an application that displays pages of employee data from the AdventureWorks sample database. The application uses the UpdatePanel control to refresh only the part of the page that has changed, without the page flash that occurs with a postback. This is referred to as a partial-page update. The sample application also uses the UpdateProgress control to display a status message while the partial-page update is processing.

You can see the code in action in this tutorial by clicking the Run It button. To implement the procedures in your own development environment you need:

*

Microsoft Visual Studio 2005 or Microsoft Visual Web Developer Express Edition.
*

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.
*

An ASP.NET AJAX Web site.
*

The AdventureWorks sample database. You can download and install the AdventureWorks database from the Microsoft Download Center. (Search for "SQL Server 2005 Samples and Sample Databases (December 2006)").

Creating an ASP.NET AJAX-Enabled Web Site

You can create ASP.NET AJAX-enabled Web sites in Visual Studio by using the template installed with ASP.NET AJAX.
To create an ASP.NET AJAX-enabled Web Site

1.

Start Visual Studio.
2.

In the File menu, click New Web Site.

The New Web Site dialog box is displayed.
3.

Under Visual Studio installed templates, select ASP.NET AJAX-Enabled Web Site.
4.

Enter a location and a language, and then click OK.

Adding an UpdatePanel Control to an ASP.NET Web Page

After you create an AJAX-enabled Web site, you create an ASP.NET Web page that includes an UpdatePanel control. Before you add an UpdatePanel control to the page, you must add a ScriptManager control. The UpdatePanel control relies on the ScriptManager control to manage partial-page updates.
To create a new ASP.NET Web page

1.

In Solution Explorer, right-click the name of the site and then click Add New Item.

The Add New Item dialog box is displayed.
2.

Under Visual Studio installed templates, select Web Form.
3.

Name the new page Employees.aspx and clear the Place code in separate file check box.
4.

Select the language you want to use.
5.

Click Add.
6.

Switch to Design view.
7.

In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page.
UpdatePanel Tutorial
8.

Drag an UpdatePanel control from the toolbox and drop it underneath the ScriptManager control.
UpdatePanel Tutorial

Adding Content to an UpdatePanel Control

The UpdatePanel control performs partial-page updates and identifies content that is updated independently of the rest of the page. In this part of the tutorial, you will add a data-bound control that displays data from the AdventureWorks database.
To add content to an UpdatePanel control

1.

From the Data tab of the toolbox, drag a GridView control into the editable area of the UpdatePanel control.
2.

In the GridView Tasks menu, click Auto Format.
3.

In the Auto Format panel, under Select a scheme, select Colorful and then click OK.
4.

In the GridView Tasks menu, select from the Choose Data Source list.

The Data Source Configuration wizard is displayed.
5.

Under Where will the application get data from, select Database and then click OK.
6.

In the Configure Data Source wizard, for the Choose Your Data Connection step, configure a connection to the AdventureWorks database and then click Next.
7.

For the Configure the Select Statement step, select Specify a custom SQL statement or stored procedure and then click Next.
8.

In the SELECT tab of the Define Custom Statement or Stored Procedures step, enter the following SQL statement:

SELECT FirstName, LastName FROM HumanResources.vEmployee ORDER BY LastName, FirstName

9.

Click Next.
10.

Click Finish.
11.

In the GridView Tasks menu, select the Enable paging check box.
12.

Save your changes, and then press CTRL+F5 to view the page in a browser.

Notice that there is no page flash when you select different pages of data. This is because the page is not performing a postback and updating the whole page every time.

Adding an UpdateProgress Control to the Page

The UpdateProgress control displays a status message while new content for an UpdatePanel control is being requested.
To add an UpdateProgress control to the page

1.

From the AJAX Extensions tab of the toolbox, drag an UpdateProgress control onto the page and drop it underneath the UpdatePanel control.
2.

Select the UpdateProgress control, and in the Properties window, set the AssociatedUpdatePanelID property to UpdatePanel1.

This associates the UpdateProgress control with the UpdatePanel control that you added previously.
3.

In the editable area of the UpdateProgress control, type Getting Employees ... .
4.

Save your changes, and then press CTRL+F5 to view the page in a browser.

If there is a delay while the page runs the SQL query and returns the data, the UpdateProgress control displays the message that you entered into the UpdateProgress control.

Adding a Delay to the Sample Application

If your application updates each page of data quickly, you might not see the content of the UpdateProgress control on the page. The UpdateProgress control supports a DisplayAfter property that enables you to set a delay before the control is displayed. This prevents the control from flashing in the browser if the update occurs very fast. By default, the delay is set to 500 milliseconds (.5 second), meaning that the UpdateProgress control will not be displayed if the update takes less than half a second.

In a development environment, you can add an artificial delay to your application to make sure that the UpdateProgress control is functioning as intended. This is an optional step and is only for testing your application.
To add a delay to the sample application

1.

Inside the UpdatePanel control, select the GridView control.
2.

In the Properties window, click the Events button.
3.

Double-click the PageIndexChanged event to create an event handler.
4.

Add the following code to the PageIndexChanged event handler to artificially create a three-second delay:
CS

//Include three second delay for example only.
System.Threading.Thread.Sleep(3000);

VB

'Include three second delay for example only.
System.Threading.Thread.Sleep(3000)

note

The handler for the PageIndexChanged event intentionally introduces a delay for this tutorial. In practice, you would not introduce a delay. Instead, the delay would be the result of server traffic or of server code that takes a long time to process, such as a long-running database query.
5.

Save your changes, and then press CTRL+F5 to view the page in a browser.

Because there is now a three-second delay every time that you move to a new page of data, you will be able to see the UpdateProgress control.


Introduction to the UpdatePanel Control
Introduction

In this tutorial you will add partial-page update support to a Web page by using two Microsoft ASP.NET 2.0 AJAX Extensions server controls: the ScriptManager control and the UpdatePanel control. These controls remove the requirement to refresh the whole page with each postback, which improves the user experience. For more background on partial-page updates, see Partial-Page Rendering Overview.

You can see the code in action in this tutorial by clicking the Run It buttons. To implement the procedures in your own development environment you need:

*

Microsoft Visual Studio 2005 or Microsoft Visual Web Developer Express Edition.
*

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.
*

An ASP.NET AJAX Web site.

To use an UpdatePanel control

1.

Create a new page and switch to Design view.
2.

In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page.
UpdatePanel Tutorial
3.

Double-click the UpdatePanel control to add it to the page.
UpdatePanel Tutorial
4.

Click inside the UpdatePanel control and then in the Standard tab of the toolbox, double-click the Label and Button controls to add them to the UpdatePanel control.
note

Make sure that you add the Label and Button controls inside the UpdatePanel control.
5.

Set the Text property of the Label to Panel created.
UpdatePanel Tutorial
6.

Double-click the Button control to add a handler for the button's Click event.
7.

Add the following code to the Click handler, which sets the value of the label in the panel to the current time.
CS

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Refreshed at " +
DateTime.Now.ToString();
}

VB

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = "Refreshed at " & _
DateTime.Now.ToString()
End Sub

8.

Save your changes and press CTRL+F5 to view the page in a browser.
9.

Click the button.

Notice that the text in the panel changes to display the last time the panel's content was refreshed. This text is set in the button's Click event handler.

To see the full example in action, click the Run It button. The example is styled to better show the region of the page that the UpdatePanel represents.
Run View

The panel content changes every time that you click the button, but the whole page is not refreshed. By default, the ChildrenAsTriggers property of an UpdatePanel control is true. When this property is set to true, controls inside the panel participate in partial-page updates when any control in the panel causes a postback.

Understanding the Benefits of the UpdatePanel Control

You can understand the benefits of the UpdatePanel control best by adding some controls to the page that are not included in the update panel. You can then see how their behavior differs from the controls inside the update panel.
To demonstrate the benefits of using UpdatePanel control

1.

Create a new page and switch to in Design view.
2.

In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page.
3.

Double-click the UpdatePanel control to add it to the page.
UpdatePanel Tutorial
4.

Click inside the UpdatePanel control and then in the Standard tab of the toolbox, double-click a Calendar control to add it to the UpdatePanel control.
note

Make sure that you add the Calendar control inside the UpdatePanel control.
UpdatePanel Tutorial
5.

Click outside the UpdatePanel control and then add a second Calendar control to the page.

This control will not be part of the UpdatePanel control.
UpdatePanel Tutorial
6.

Save your changes and then press CTRL+F5 view the page in a browser.
7.

Navigate to the previous or next month in the calendar that is inside the UpdatePanel control.

The displayed month changes without refreshing the whole page.
8.

Navigate to the previous or next month in the calendar that is outside the UpdatePanel control

The whole page is refreshed.

To see the full example in action, click the Run It button. The example is styled to better show the region of the page that the UpdatePanel represents.
Run View

Refreshing an UpdatePanel Control with an External Button

By default, a postback control (such as a button) inside an UpdatePanel control causes a partial-page update. By default, a button or other control outside an UpdatePanel control causes the whole page to be refreshed, as you have seen.

You can also configure a control outside the update panel to be a trigger that refreshes just the update panel.
To refresh of an UpdatePanel control with an external button

1.

Create a new page and switch to Design view.
2.

In the AJAX Extensions tab of the toolbox, double-click the ScriptManager and UpdatePanel controls to add one of each control to the page.
UpdatePanel Tutorial
3.

Click inside the UpdatePanel control, and then in the Standard tab of the toolbox, double-click the Label control to add it to the UpdatePanel control.
4.

Set the Text property of the label to Panel created.
UpdatePanel Tutorial
5.

Click outside the UpdatePanel control and then add a Button control.
UpdatePanel Tutorial
6.

Double-click the Button control to add a handler for the button's Click event.
7.

Add the following code to the Click handler, which sets the value of the label in the panel to the current time.
CS

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Refreshed at " +
DateTime.Now.ToString();
}

VB

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = "Refreshed at " & _
DateTime.Now.ToString()
End Sub

8.

Switch to Design view, select the UpdatePanel, and then view the Properties window.
UpdatePanel Tutorial
note

If the Properties window is not displayed, press F4.
9.

In the Triggers field, double-click the ellipsis (…) button.

The UpdatePanelTrigger Collection Editor dialog box is displayed.
UpdatePanel Tutorial
10.

Click Add to add a new trigger.
11.

In the ControlID field of the trigger properties, use the drop-down list to select Button1.
UpdatePanel Tutorial

In this example, the EventName property of the trigger was not specified. Therefore, the button's default event (the Click event) will trigger the refresh of the UpdatePanel control.
12.

Click OK in collection editor.
13.

Save your changes and then press CTRL+F5 view the page in a browser.
14.

Click the button.

The text in the panel changes to display the time that the panel's content was refreshed.
15.

Click the button several more times.

The time changes, but the whole page is not refreshed.

Clicking the button outside the UpdatePanel refreshes the panel's content because you configured the button to be a trigger for the UpdatePanel control. A button that is a trigger performs an asynchronous postback when you click it, and causes a refresh of the associated update panel. This behavior resembles the behavior of the first example in this tutorial, where the button was inside the UpdatePanel.


Introduction to the UpdateProgress Control
Introduction

In this tutorial you will use UpdateProgress controls to display the progress of partial-page updates. If a page contains UpdatePanel controls, you can also include UpdateProgress controls to keep users informed about the status of partial-page updates. You can use one UpdateProgress control to represent the progress of partial-page updates for the whole page. Alternatively, you can include an UpdateProgress control for every UpdatePanel control. Both of these patterns are shown in this tutorial.

You can see the code in action in this tutorial by clicking the Run It buttons. To implement the procedures in your own development environment you need:

*

Microsoft Visual Studio 2005 or Visual Web Developer Express Edition.
*

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.
*

An ASP.NET AJAX Web site.

Using a Single UpdateProgress Control

You will begin by using a single UpdateProgress control to show the progress for all partial-page updates on the page.
To use a single UpdateProgress control for the whole page

1.

Create a new page and switch to Design view.
2.

In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page.
3.

Double click the UpdatePanel control to add it to the page.
UpdatePanel Tutorial
4.

Double-click the UpdateProgress control to add it to the page.
5.

Inside the UpdateProgress control, add the text Processing….
UpdateProgress Tutorial
6.

Inside the UpdatePanel control add a Label control and a Button control.
7.

Set the Text property of the Label control to Initial Page Rendered.
UpdateProgress Tutorial
8.

Double click the Button control to add a handler for the button's Click event.
9.

Add the following code to the Click handler, which artificially creates a three-second delay and then displays the current time.
CS

protected void Button1_Click(object sender, EventArgs e)
{
// Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000);
Label1.Text = "Page refreshed at " +
DateTime.Now.ToString();
}

VB

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000)
Label1.Text = "Page refreshed at " & _
DateTime.Now.ToString()
End Sub

note

The handler for the Click event intentionally introduces a delay for this tutorial. In practice, you would not introduce a delay. Instead, the delay would be the result of server traffic or of server code that takes a long time to process, such as a long-running database query.
10.

Save your changes and then press CTRL+F5 to view the page in a browser.
11.

Click the button.

After a short delay, the progress message is displayed. When the handler for the Click event has finished, the progress message is hidden and the time that is displayed in the panel is updated.

To see the full example in action, click the Run It button. The example is styled to better show the region of the page that the UpdatePanel represents.
Run View

Using Multiple UpdateProgress Controls

One UpdateProgress control on the page can show a progress message for all UpdatePanel controls on the page. Asynchronous postbacks originating inside an UpdatePanel control cause the UpdateProgress control to display its message. Postbacks from controls that are triggers for the panel also display the message.

You can associate the UpdateProgress control with a single UpdatePanel control by setting the progress control's AssociatedUpdatePanelID property. In that case, the UpdateProgress control displays a message only when a postback originates inside the associated UpdatePanel control.

In the next procedure, two UpdateProgress controls are added to a page, each associated with a different UpdatePanel control.
To use multiple UpdateProgress controls on a page

1.

Create a new page and switch to Design view.
2.

In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page.
3.

Double-click the UpdatePanel control two times to add two instances of the control to the page.
UpdateProgress Tutorial
4.

In each UpdatePanel control, add a Label control and a Button control.
5.

Set the Text property of both Label controls to Panel Initially Rendered.
UpdateProgress Tutorial
6.

Double-click each Button control to add a handler for each button's Click event.
7.

Add the following code to each Click handler, which artificially creates a three-second delay and then displays the current time.
CS

protected void Button1_Click(object sender, EventArgs e)
{
// Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000);
Label1.Text = "Page refreshed at " +
DateTime.Now.ToString();
}

protected void Button2_Click(object sender, EventArgs e)
{
// Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000);
Label2.Text = "Page refreshed at " +
DateTime.Now.ToString();

}

VB

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000)
Label1.Text = "Page refreshed at " & _
DateTime.Now.ToString()
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000)
Label1.Text = "Page refreshed at " & _
DateTime.Now.ToString()
End Sub

8.

Switch to Design view.
9.

Click inside the first UpdatePanel control and add an UpdateProgress control.
10.

Inside the UpdateProgress control, add the text Panel1 Updating.

This sets the ProgressTemplate property.
11.

Select the UpdateProgress control, and in the Properties window, set the AssociatedUpdatePanelID property to UpdatePanel1.
UpdateProgress Tutorial
12.

Click inside the second UpdatePanel control and add a second UpdateProgress control.
13.

Set the text of the UpdateProgress control to Panel2 Updating and set its AssociatedUpdatePanelID property to UpdatePanel2.
UpdateProgress Tutorial
14.

Save your changes, and then press CTRL+F5 to view the page in a browser.
15.

Click the button in the first panel.

After a short delay, the progress message associated with the first panel is displayed. The other UpdateProgress control is not displayed.
16.

Click the button in the second panel.

The progress message associated with the second panel is displayed.
note

By default, starting a new asynchronous postback while an earlier one is in progress cancels the first postback. For more information, see Giving Precedence to a Specific Asynchronous Postback.
17.
Introduction to the Timer Control
Introduction

In this tutorial you will update part of a Web page at a timed interval by using three Microsoft ASP.NET 2.0 AJAX Extensions server controls: the ScriptManager control, the UpdatePanel control, and the Timer control. Adding these controls to a page eliminates the need to refresh the whole page with each postback. Only the contents of the UpdatePanel control will be updated.

For more information about partial-page rendering, see Partial-Page Rendering Overview.

To implement the procedures in this tutorial you need:
18.

Microsoft Visual Studio 2005 or Visual Web Developer Express Edition.
19.

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.
20.

An ASP.NET AJAX Web site.

To refresh an UpdatePanel control at a timed interval

1.

Create a new page and switch to Design view.
2.

If the page does not already contain a ScriptManager control, in the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to the page.
3.

In the toolbox, double-click the UpdatePanel control to add it to the page.
4.

Click inside the UpdatePanel control and then double-click the Timer control to add it to the UpdatePanel control.
note

The Timer control can work as a trigger either inside or outside an UpdatePanel control. This example shows how to use the Timer control inside an UpdatePanel control. For an example of using a Timer control as a trigger outside an UpdatePanel control, see Using the Timer Control with Multiple UpdatePanel Controls.
5.

Set the Interval property of the Timer control to 10000.

The Interval property is defined in milliseconds, so that setting the Interval property to 10,000 milliseconds will refresh the UpdatePanel control every 10 seconds.
note

In this example, the timer interval is set to 10 seconds. That way, when you run the example, you do not have to wait a long time to see the results. However, each timer interval causes a postback to the server and causes network traffic. Therefore, in a production applications, you should set the interval to the longest time that is still practical for your application.
6.

Click inside the UpdatePanel control and then in the Standard tab of the toolbox, double-click the Label control to add it to the UpdatePanel control.
note

Make sure that you add the Label control inside the UpdatePanel control.
7.

Set the label's Text property to Panel not refreshed yet.
8.

Click outside the UpdatePanel control and double-click the Label control to add a second label outside the UpdatePanel control.
note

Make sure that you add the second Label control outside the UpdatePanel control.
9.

Double-click the Timer control to create a handler for the Tick event.
10.

Add code that sets the Text property of the Label1 control to the current time.
11.

Create a Page_Load handler and add code that sets the Text property of the Label2 control to the time that the page is created.
12.

Switch to Source view.

Make sure that the markup for the page resembles the following:
cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label2.Text = "Page created at: " +
DateTime.Now.ToLongTimeString();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString();
}
}

vb

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label2.Text = "Page created at: " & _
DateTime.Now.ToLongTimeString()
End Sub

Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = "Panel refreshed at: " & _
DateTime.Now.ToLongTimeString()

End Sub
End Class

13.

Save your changes and press CTRL+F5 to view the page in a browser.
14.

Wait at least 10 seconds for panel to refresh.

The text inside the panel changes to display the last time that the panel's content was refreshed. However, the text outside the panel is not refreshed.

Review

This tutorial introduced the basic concepts of using a Timer control and an UpdatePanel control to enable partial-page updates. You must add a ScriptManager control to any page that contains an UpdatePanel control or Timer control. By default, a Timer control inside the panel will cause just the panel to refresh during an asynchronous postback. A Timer control outside a panel can cause the UpdatePanel to be refreshed if it is configured as a trigger for the panel.

The next step is to learn about how to use the Timer control outside an UpdatePanel control and about how to use the timer to update more than one UpdatePanel control. For information about these tasks, see Using the Timer Control with Multiple UpdatePanel Controls.


ASP.NET AJAX Server Controls


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 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
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
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 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 element inside the 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 control’s content is updated on every postback that originates from anywhere on the page. This includes asynchronous postbacks from controls that are inside other UpdatePanel controls, and postbacks from controls that are not inside UpdatePanel controls.
*

If the UpdateMode property is set to Conditional, the UpdatePanel control’s content is updated when one of the following is true:
o

When the postback is caused by a trigger for that UpdatePanel control.
o

When you explicitly call the UpdatePanel control's Update() method.
o

When the UpdatePanel control is nested inside another UpdatePanel control and the parent panel is updated.
o

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

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

UpdatePanel Control Tutorials
Introduction

The topics in this section provide examples of how to use the UpdatePanel control to enable partial-page rendering in an ASP.NET Web page.
In This Section

Introduction to the UpdatePanel Control

Provides examples of how to use the UpdatePanel control to enable ASP.NET Web pages to participate in partial-page rendering.
Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls

Provides examples of how to use multiple UpdatePanel controls on a page, and of how to trigger an update by using a control outside the UpdatePanel control.
Using the UpdatePanel Control with Data-Bound Controls

Provides examples of how to use data-bound controls inside UpdatePanel controls and of how to create and refresh UpdatePanel controls programmatically.
Using the UpdatePanel Control with Master Pages

Provides examples of how to use the UpdatePanel control with ASP.NET master pages, which includes how to register a control on the master page that updates content on the content page.
Using the UpdatePanel Control with User Controls

Provides examples of how to use the UpdatePanel control with ASP.NET user controls.
Using the UpdatePanel Control with a Web Service

Provides an example of how to use the UpdatePanel control with a Web service, and of how to persist data between asynchronous postbacks that is retrieved by the service.
Customizing Error Handling for UpdatePanel Controls

Provides examples of how to customize error handling when you use UpdatePanel controls.
Animating UpdatePanel Controls

Provides an example of how to handle events of the PageRequestManager class to animate a panel that was updated during an asynchronous postback.
Canceling an Asynchronous Postback

Provides an example of how to handle the initializeRequest event of the PageRequestManager class to cancel the asynchronous postback that is currently executing.
Giving Precedence to a Specific Asynchronous Postback

Provides an example of how to handle the InitializeRequest event of the PageRequestManager class to make sure that an asynchronous postback from a specified control finishes before another postback is started.
Working with PageRequestManager Events

Provides a summary of the PageRequestManager events that can be used to customize partial-page updates.


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

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
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 element can contain HTML and markup. The following example shows how to specify a message for an UpdateProgress control.
CS



An update is in progress...



VB



An update is in progress...



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 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 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
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
element for the control has its display style property set to block and its visibility initially set to hidden.
Putting UpdateProgress Controls on the Page

You can put UpdateProgress controls inside or outside UpdatePanel controls. A UpdateProgress control is displayed whenever the UpdatePanel control it is associated with is updated as a result of an asynchronous postback. This is true even if the UpdateProgress control is inside another UpdatePanel control.

If an UpdatePanel control is inside another update panel, a postback that originates inside the child panel causes any UpdateProgress controls associated with the child panel to be displayed. It also displays any UpdateProgress controls associated with the parent panel. If a postback originates from an immediate child control of the parent panel, only the UpdateProgress controls associated with the parent panel are displayed. This follows the logic for how postbacks are triggered.
Specifying When UpdateProgress Controls Are Displayed

You can programmatically control when an UpdateProgress control is displayed by using the JavaScript beginRequest and endRequest events of the PageRequestManager class. In the beginRequest event handler, display the DOM element that represents the UpdateProgress control. In the endRequest event handler, hide the element.

You must provide client script to show and hide an UpdateProgress control in the following circumstances:

*

During a postback from a control that is registered as an asynchronous postback trigger for the update panel, but that the UpdateProgress control is not associated with.
*

During postbacks from controls that are registered programmatically as asynchronous postback controls by using the RegisterAsyncPostBackControl(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 the server and exposes events and methods for custom client scripting.


UpdateProgress Control Tutorials
Introduction

The topics in this section provide examples of using the UpdateProgress control to display status during the partial-page rendering.
In This Section

Introduction to the UpdateProgress Control

Provides examples of how to use one UpdateProgress control to show partial-page update status for all UpdatePanel controls on the page, and two UpdateProgress controls to show status for different UpdatePanel controls.
Programming UpdateProgress Controls in Client Script

Provides examples of how to customize the behavior of the UpdateProgress control with script to cancel asynchronous postbacks and to toggle visibility of the progress message.

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
*

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

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.



UpdateMode="Conditional">


Interval="120000"
OnTick="Timer1_Tick">



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.



OnTick="Timer1_Tick">




EventName="Tick" />





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" %>


















Stock price is

as of








Update stock price every:








Page loaded at





vb

<%@ Page Language="VB" AutoEventWireup="true" %>



















Stock price is

as of











Page originally created at





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

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

Extending JavaScript with ASP.NET AJAX

ASP.NET AJAX Introduction-2

Client Scripting

Extending JavaScript with ASP.NET AJAX
Introduction

Microsoft ASP.NET AJAX enables you to write rich, interactive applications in JavaScript that target the browser. The Microsoft AJAX Library adds a type system and extensions to JavaScript objects in order to provide namespaces, inheritance, interfaces, enumerations, reflection, and helpers for strings and arrays. These additions provide functionality similar to the .NET Framework. They enable you to write ASP.NET AJAX applications in a structured way that improves maintainability, makes it easier to add features, and makes it easier to layer functionality.

In this section you will learn how to use the following JavaScript Microsoft AJAX Library features:

*

Classes
*

Namespaces
*

Inheritance
*

Interfaces
*

Enumerations
*

Reflection

Classes, Members, and Namespaces

Classes are reference types. All classes in JavaScript derive from object. (Similarly, in the .NET Framework class library, all classes derive from Object.) Classes in ASP.NET AJAX enable you to create objects and components that derive from base classes in the Microsoft AJAX Library by using an object-oriented programming model.

Classes can have four kinds of members: fields, properties, methods, and events. Fields and properties are name/value pairs that describe characteristics of an instance of a class. Fields are composed of primitive types and are accessed directly, as in the following example:

myClassInstance.name="Fred"

With properties, the value can be any primitive or reference type and is accessed by get and set accessor methods. In ASP.NET AJAX, the get and set accessors are separate functions, which by convention use the prefix "get_" or "set_" in the function name. For example, to get or set a value for a property such as cancel, you call the get_cancel or set_cancel methods.

A method is a function that performs an action instead of just returning a property value. Both methods and properties are illustrated in the examples in this topic.

Events are programmatic notifications that particular actions have occurred. When an event is raised, it can call one or more functions, referred to as handlers, to perform tasks that were waiting for that event. For more information about events in ASP.NET AJAX, see ASP.NET AJAX Client Life-Cycle Events.

A namespace is a logical grouping of related classes (types). Namespaces enable you to group common functionality. The following example demonstrates how to add a Person class to the Demo namespace using the Type.registerNamespace and .registerClass methods.

To enable ASP.NET AJAX functionality for an ASP.NET Web page, you must add an control to the page. When the page is rendered, the appropriate script references to ASP.NET AJAX libraries are generated automatically. The following example shows a page with an control.
cs



The following example shows how to register the namespace, create the class, and then register the class.
cs

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

Demo.Person.prototype = {

getFirstName: function() {
return this._firstName;
},

getLastName: function() {
return this._lastName;
},

getName: function() {
return this._firstName + ' ' + this._lastName;
},

dispose: function() {
alert('bye ' + this.getName());
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);

// Notify ScriptManager that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


To see a Web page that uses the preceding script file, click the Run It button.

Access Modifiers

Most object-oriented programming languages include the concept of access modifiers, which allow you to specify under what contexts a class or member is available, such as to outside programs, internal classes within the same namespace, or only within a specific code block. There are no access modifiers in JavaScript, however ASP.NET AJAX follows the convention that members with names that start with the underscore character ("_") are considered private and not accessed outside the class they are a part of.
Inheritance

Inheritance is the ability of one class to derive from another class. A derived class automatically inherits all the fields, properties, methods and events of the base class. A derived class also adds new members or overrides existing members of the base class to change their behavior.

The following example contains two classes defined in script: Person and Employee, where Employee derives from Person. Both classes illustrate the use of private fields, and both have public properties and methods. In addition, Employee overrides the toString implementation of the Person class, and uses the base class functionality.
cs

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

Demo.Person.prototype = {
getFirstName: function() {
return this._firstName;
},

getLastName: function() {
return this._lastName;
},

getEmailAddress: function() {
return this._emailAddress;
},
setEmailAddress: function(emailAddress) {
this._emailAddress = emailAddress;
},

getName: function() {
return this._firstName + ' ' + this._lastName;
},

dispose: function() {
alert('bye ' + this.getName());
},

sendMail: function() {
var emailAddress = this.getEmailAddress();

if (emailAddress.indexOf('@') < 0) {
emailAddress = emailAddress + '@example.com';
}
alert('Sending mail to ' + emailAddress + ' ...');
},

toString: function() {
return this.getName() + ' (' + this.getEmailAddress() + ')';
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);
Demo.Employee = function(firstName, lastName, emailAddress, team, title) {
Demo.Employee.initializeBase(this, [firstName, lastName, emailAddress]);

this._team = team;
this._title = title;
}

Demo.Employee.prototype = {

getTeam: function() {
return this._team;
},
setTeam: function(team) {
this._team = team;
},

getTitle: function() {
return this._title;
},
setTitle: function(title) {
this._title = title;
},
toString: function() {
return Demo.Employee.callBaseMethod(this, 'toString') + '\r\n' + this.getTitle() + '\r\n' + this.getTeam();
}
}
Demo.Employee.registerClass('Demo.Employee', Demo.Person);

To see a Web page that uses the preceding script file, click the Run It button.

Interfaces

An interface is a logical structure that defines the input and output requirements of classes that implement it. This enables a function to interact with classes that implement the same interface regardless of what other functionality the class implements.

The following example defines a Tree base class and an IFruitTree interface. Apple and Banana, two derived classes, implement the IFruitTree interface, but the Pine class does not.
cs

Type.registerNamespace("Demo.Trees");

Demo.Trees.IFruitTree = function() {}
Demo.Trees.IFruitTree.Prototype = {
bearFruit: function(){}
}
Demo.Trees.IFruitTree.registerInterface('Demo.Trees.IFruitTree');


Demo.Trees.Tree = function(name) {
this._name = name;
}
Demo.Trees.Tree.prototype = {
returnName: function() {
return this._name;
},

toStringCustom: function() {
return this.returnName();
},

makeLeaves: function() {}
}
Demo.Trees.Tree.registerClass('Demo.Trees.Tree');


Demo.Trees.FruitTree = function(name, description) {
Demo.Trees.FruitTree.initializeBase(this, [name]);
this._description = description;
}
Demo.Trees.FruitTree.prototype.bearFruit = function() {
return this._description;
}
Demo.Trees.FruitTree.registerClass('Demo.Trees.FruitTree', Demo.Trees.Tree, Demo.Trees.IFruitTree);

Demo.Trees.Apple = function() {
Demo.Trees.Apple.initializeBase(this, ['Apple', 'red and crunchy']);
}
Demo.Trees.Apple.prototype = {
makeLeaves: function() {
alert('Medium-sized and desiduous');
},
toStringCustom: function() {
return 'FruitTree ' + Demo.Trees.Apple.callBaseMethod(this, 'toStringCustom');
}
}
Demo.Trees.Apple.registerClass('Demo.Trees.Apple', Demo.Trees.FruitTree);

Demo.Trees.GrannySmith = function() {
Demo.Trees.GrannySmith.initializeBase(this);
// You must set the _description feild after initializeBase
// or you will get the base value.
this._description = 'green and sour';
}
Demo.Trees.GrannySmith.prototype.toStringCustom = function() {
return Demo.Trees.GrannySmith.callBaseMethod(this, 'toStringCustom') + ' ... its GrannySmith!';
}
Demo.Trees.GrannySmith.registerClass('Demo.Trees.GrannySmith', Demo.Trees.Apple);


Demo.Trees.Banana = function(description) {
Demo.Trees.Banana.initializeBase(this, ['Banana', 'yellow and squishy']);
}
Demo.Trees.Banana.prototype.makeLeaves = function() {
alert('Big and green');
}
Demo.Trees.Banana.registerClass('Demo.Trees.Banana', Demo.Trees.FruitTree);



Demo.Trees.Pine = function() {
Demo.Trees.Pine.initializeBase(this, ['Pine']);
}
Demo.Trees.Pine.prototype.makeLeaves = function() {
alert('Needles in clusters');
}
Demo.Trees.Pine.registerClass('Demo.Trees.Pine', Demo.Trees.Tree);


To see a Web page that uses the preceding script file, click the Run It button.

Enumerations

An enumeration is a class that contains a set of named integer constants. You access the values like properties, as in the following example:

myObject.color = myColorEnum.red

Enumerations provide an easily readable alternative to integer representations. For more information about enumerations in ASP.NET AJAX, see registerEnum Method.

The following example defines an enumeration of named colors that represent hexadecimal values.
cs

Type.registerNamespace("Demo");

// Define an enumeration type and register it.
Demo.Color = function(){};
Demo.Color.prototype =
{
Red: 0xFF0000,
Blue: 0x0000FF,
Green: 0x00FF00,
White: 0xFFFFFF
}
Demo.Color.registerClass("Demo.Color");

To see a Web page that uses the preceding script file, click the Run It button.
Reflection

Reflection is the ability to examine the structure and components of a program at run time. The APIs that implement reflection are extensions of the Type class. These methods enable you to collect information about an object, such as what it inherits from, whether it implements a particular interface, and whether it is an instance of a particular class.
Creating Custom Client Script in ASP.NET AJAX
Introduction

Microsoft ASP.NET AJAX provides features that help you create client script and integrate it into ASP.NET applications. This includes a type system and extensions to existing ECMAScript (JavaScript) objects to give them the richness of .NET Framework classes. It also provides the ScriptManager control to manage these script libraries and any custom script in your application.
Creating Scripts

The Microsoft AJAX Library includes features that contribute to a richer, more powerful JavaScript development experience.

The Type class adds object-oriented features such as classes and inheritance to JavaScript programming. Any JavaScript object that is registered by using the Type class automatically has access to this functionality. For more information, see Extending JavaScript with ASP.NET AJAX.

The following example shows how to use the Type class to create and register a namespace and a class in a JavaScript file:
cs

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
this._firstName = firstName;
this._lastName = lastName;
this._emailAddress = emailAddress;
}

Demo.Person.prototype = {

getFirstName: function() {
return this._firstName;
},

getLastName: function() {
return this._lastName;
},

getName: function() {
return this._firstName + ' ' + this._lastName;
},

dispose: function() {
alert('bye ' + this.getName());
}
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);

// Notify ScriptManager that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


Extensions to JavaScript base types provide additional functionality for those types. For more information about these extensions, see the following topics:

*

Array Type Extensions
*

Boolean Type Extensions
*

Date Type Extensions
*

Error Type Extensions
*

Number Type Extensions
*

Object Type Extensions
*

String Type Extensions

The Sys.Debug class provides extensive debugging capabilities. For more information, see ASP.NET AJAX Debugging and Tracing Overview and the Sys.Debug class overview.

Component developers can create debug and retail versions of script files that are automatically managed by the ScriptManager control. You can identify debug versions of script files by including ".debug" as part of the script file name. For example, the following script file names identify retail and debug versions of a file:

*

Retail: MyScript.js
*

Debug: MyScript.debug.js

Integrating Client Script into ASP.NET Web Applications

Any ASP.NET Web page can access a script file by referring to it in a

However, a script invoked in this manner cannot participate in partial-page rendering or access certain components of the Microsoft AJAX Library. To make a script file available for partial-page rendering in an ASP.NET AJAX Web application, the script must be registered with the ScriptManager control on the page. To register a script file, create a ScriptReference object that points to the file question and that adds it to the Scripts collection. The following example shows how to do this in markup:







For script files to be processed correctly by the ScriptManager control, each file must include a call to the Sys.Application.notifyScriptLoaded method at the end of the file. This call notifies the application that the file has finished loading. The following example shows the code to use for this purpose:

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

If your script is embedded in an assembly, you do not have to include a notification statement in the script. You also do not have to specify a path attribute in the script reference. However, you must provide the name of the assembly without the file name extension, as shown in the following example:




Name="MyScript.js" Assembly="MyScriptAssembly"/>



note

This scenario is not common for page developers, because most controls with embedded script libraries reference their scripts internally. For more information, see Embedding a JavaScript File as a Resource in an Assembly.

You can also register scripts programmatically by creating script references in code and then adding them to the Scripts collection. For more information, see Dynamically Assigning ASP.NET AJAX Script References.

You can register scripts that are required for partial-page updates by using the registration methods of the ScriptManager control. You can use these methods in the following ways:

*

To generate client script in code, build a block of script as a string and pass it to the RegisterClientScriptBlock) method.
*

To add standalone script files that have no Microsoft AJAX Library dependencies, use the RegisterClientScriptInclude) method.
*

To add script files that are embedded in an assembly, use the RegisterClientScriptResource method.
note

Scripts that are registered by using these methods do not have localization support.

For a complete list of script-registration methods and their uses, see the ScriptManager control overview.

Any script blocks or inline script that you are registering must be inside the page's
element. Otherwise, the script is not registered with the ScriptManager control and cannot access ASP.NET AJAX functionality. For more information, see initialize Method.
Embedding a JavaScript File as a Resource in an Assembly
Introduction

In this tutorial, you will include a JavaScript file as an embedded resource in an assembly. You embed a JavaScript file when you have a client-script component that must be distributed with an assembly that you have created. For example, you might create a custom ASP.NET server control that uses JavaScript files to implement ASP.NET AJAX functionality. You can embed the JavaScript files in the assembly, and they can then be referenced from a Web application that registers the assembly.

To implement the procedures in this tutorial you need:

*

Microsoft Visual Studio 2005.
note

You cannot use Visual Web Developer 2005 Express Edition, because Visual Web Developer Express Edition does not enable you to create the class library project required in the tutorial.
*

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.

Creating an Assembly that Contains an Embedded JavaScript File

To begin, you will create a file that contains the JavaScript code that you want to embed in the assembly.
To embed a client script file in an assembly

1.

In Visual Studio, create a new class library project named SampleControl.
2.

Add references to the System.Web, System.Drawing, and System.Web.Extensions namespaces to the project.
3.

Add a new JScript file named UpdatePanelAnimation.js to the project.
4.

Add the following code to the UpdatePanelAnimation.js file:
CS

BorderAnimation = function(color) {
this._color = color;
}

BorderAnimation.prototype = {
animate: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '2px';
s.borderColor = this._color;
s.borderStyle = 'solid';

window.setTimeout(
function() {{
s.borderWidth = 0;
}},
500);
}
}


vb

BorderAnimation = function(color) {
this._color = color;
}

BorderAnimation.prototype = {
animate: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '2px';
s.borderColor = this._color;
s.borderStyle = 'solid';

window.setTimeout(
function() {{
s.borderWidth = 0;
}},
500);
}
}


The code contains a JavaScript function that temporarily displays a colored border around an UpdatePanel control.
5.

In the Properties window for the UpdatePanelAnimation.js file, set Build Action to Embedded Resource.
Set script file to embedded resource
6.

Add a class file named CustomControl to the project.
7.

Replace any code in the CustomControl file with the following code:
CS

using System;
using System.Drawing;
using System.Web.UI;
using System.Web;
using System.Globalization;

namespace SampleControl
{
public class UpdatePanelAnimationWithClientResource : Control
{
private string _updatePanelID;
private Color _borderColor;
private Boolean _animate;
public Color BorderColor
{
get
{
return _borderColor;
}
set
{
_borderColor = value;
}
}

public string UpdatePanelID
{
get
{
return _updatePanelID;
}
set
{
_updatePanelID = value;
}
}

public Boolean Animate
{
get
{
return _animate;
}
set
{
_animate = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Animate)
{

UpdatePanel updatePanel = (UpdatePanel)FindControl(UpdatePanelID);

string script = String.Format(
CultureInfo.InvariantCulture,
@"
Sys.Application.add_load(function(sender, args) {{
var {0}_borderAnimation = new BorderAnimation('{1}');
var panelElement = document.getElementById('{0}');
if (args.get_isPartialLoad()) {{
{0}_borderAnimation.animate(panelElement);
}}
}})
",
updatePanel.ClientID,
ColorTranslator.ToHtml(BorderColor));


ScriptManager.RegisterStartupScript(
this,
typeof(UpdatePanelAnimationWithClientResource),
ClientID,
script,
true);
}
}
}
}

vb

Imports System.Web.UI
Imports System.Drawing
Imports System.Globalization

Public Class UpdatePanelAnimationWithClientResource
Inherits Control

Private _updatePanelID As String
Private _borderColor As Color
Private _animate As Boolean

Public Property BorderColor() As Color
Get
Return _borderColor
End Get
Set(ByVal value As Color)
_borderColor = value
End Set
End Property

Public Property UpdatePanelID() As String
Get
Return _updatePanelID
End Get
Set(ByVal value As String)
_updatePanelID = value
End Set
End Property

Public Property Animate() As Boolean
Get
Return _animate
End Get
Set(ByVal value As Boolean)
_animate = value
End Set
End Property

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
MyBase.OnPreRender(e)
If (Animate) Then

Dim updatePanel As UpdatePanel = CType(Me.FindControl(UpdatePanelID), UpdatePanel)

Dim script As String = String.Format( _
CultureInfo.InvariantCulture, _
"Sys.Application.add_load(function(sender, args) {{var {0}_borderAnimation = new BorderAnimation('{1}');var panelElement = document.getElementById('{0}');if (args.get_isPartialLoad()) {{{0}_borderAnimation.animate(panelElement);}}}});", _
updatePanel.ClientID, _
ColorTranslator.ToHtml(BorderColor))


ScriptManager.RegisterStartupScript( _
Me, _
GetType(UpdatePanelAnimationWithClientResource), _
ClientID, _
script, _
True)
End If
End Sub
End Class

This class contains properties for customizing the border that is displayed around the UpdatePanel control. The code also registers JavaScript code to use in a Web page. The code creates a handler for the load event of the Sys.Application object. The animate function in the UpdatePanelAnimation.js file is called when a partial-page update is processed.
8.

Add the following line to the AssemblyInfo file.
CS

[assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")]

vb



note

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.

The WebResource definition must include the default namespace of the assembly and the name of the .js file.
9.

Build the project.

When compilation finishes, you will have an assembly named SampleControl.dll. The JavaScript code in the UpdatePanelAnimation.js file is embedded in this assembly as a resource.

Referencing the Embedded Script File

You can now reference the embedded script file in a Web application.
note

Although you can create the class library project and the Web site in the same Visual Studio solution, in this tutorial it is not assumed that you are doing this. Having the projects in separate solutions emulates how a control developer and a page developer would work separately. However, for convenience you can create both projects in the same solution and make small adjustments to procedures in the tutorial.
To reference the embedded script file

1.

In Visual Studio, create a new AJAX-enabled Web site.
2.

Create a Bin folder in the root directory of the Web site.
3.

Copy SampleControl.dll from the Bin\Debug or Bin\Release directory of the class library project to the Bin folder of the Web site.
note

If you created the class library project and the Web site in the same Visual Studio solution, you can add a reference from the class library project to the Web site. For details, see How to: Add a Reference to a Visual Studio Project in a Web Site.
4.

Replace the code in the Default.aspx file with the following code:
CS

<%@ Page Language="C#" %>
<%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">












EnablePartialRendering="True"
runat="server">







ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >


UpdateMode="Conditional"
runat="server">


runat="server">








vb

<%@ Page Language="VB" AutoEventWireup="true" %>

<%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">










EnablePartialRendering="True"
runat="server">







ID="UpdatePanelAnimator1"
BorderColor="Green"
Animate="true"
UpdatePanelID="UpdatePanel1"
runat="server" >


UpdateMode="Conditional"
runat="server">


runat="server">








This code includes an element that references the assembly and the name of the .js file that you created in the previous procedure. The name of the .js file includes a prefix that references the default namespace of the assembly.
5.

Run the project, and in the page, click dates in the calendar.

Every time that you click a date in the calendar, you see a green border around the UpdatePanel control.

Review

This tutorial showed you how to embed a JavaScript file as a resource in an assembly. The embedded script file can be accessed in a Web application that contains the assembly.

The next step is to learn how to embed localized resources in an assembly for use in client script. For more information, see Embedding Localized Resources for a JavaScript File.

Embedding Localized Resources for a JavaScript File
Introduction

In this tutorial you will include a JavaScript file as an embedded resource in an assembly, and also include localized strings for use in the JavaScript file. You embed a JavaScript file in an assembly when you have a client script component that must be distributed with the assembly. The JavaScript file can be referenced from a Web application that registers the assembly. You embed localized resources when you have to modify values that are used by the JavaScript file for different languages and cultures.

To implement the procedures in this tutorial you need:

*

Microsoft Visual Studio 2005.
note

You cannot use Visual Web Developer 2005 Express Edition, because Visual Web Developer Express Edition does not enable you to create the class library project required in the tutorial.
*

The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.

Creating an Assembly that Contains an Embedded JavaScript File

You will begin by creating an assembly (.dll file) that contains the JavaScript file that you want to treat as a resource. You will do so by creating a class library project in Visual Studio, which creates an assembly as its output.
To embed a client script file and resources in an assembly

1.

In Visual Studio, create a new class library project named LocalizingScriptResources.
2.

Add references to the System.Web and System.Web.Extensions namespaces to the project.
3.

Add a new JScript file to the project named CheckAnswer.js.
4.

Add the following code to the CheckAnswer.js file.
cs

function CheckAnswer()
{
var firstInt = $get('firstNumber').innerText;
var secondInt = $get('secondNumber').innerText;
var userAnswer = $get('userAnswer');

if ((Number.parseLocale(firstInt) + Number.parseLocale(secondInt)) == userAnswer.value)
{
alert(Answer.Correct);
return true;
}
else
{
alert(Answer.Incorrect);
return false;
}
}

vb

function CheckAnswer()
{
var firstInt = $get('firstNumber').innerText;
var secondInt = $get('secondNumber').innerText;
var userAnswer = $get('userAnswer');

if ((Number.parseLocale(firstInt) + Number.parseLocale(secondInt)) == userAnswer.value)
{
alert(Answer.Correct);
return true;
}
else
{
alert(Answer.Incorrect);
return false;
}
}

The script checks the user's result for adding two numbers. It uses the alert function to let the user know whether the answer is correct. The message displayed in the alert dialog box is read from a localized resource without a postback to the server.

A placeholder named Answer is used in the script to identify which resource files contain the localized strings. The Answer placeholder will be defined later in this procedure.
5.

In the Properties window for CheckAnswer.js, set Build Action to Embedded Resource.
Set script file to embedded resource
6.

Add a class to the project named ClientVerification.
7.

Replace any code in the ClientVerification file with the following code:
cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Resources;


namespace LocalizingScriptResources
{
public class ClientVerification : Control
{
private Button _button;
private Label _firstLabel;
private Label _secondLabel;
private TextBox _answer;
private int _firstInt;
private int _secondInt;

protected override void CreateChildControls()
{
Random random = new Random();
_firstInt = random.Next(0, 20);
_secondInt = random.Next(0, 20);

ResourceManager rm = new ResourceManager("LocalizingScriptResources.VerificationResources", this.GetType().Assembly);
Controls.Clear();

_firstLabel = new Label();
_firstLabel.ID = "firstNumber";
_firstLabel.Text = _firstInt.ToString();

_secondLabel = new Label();
_secondLabel.ID = "secondNumber";
_secondLabel.Text = _secondInt.ToString();

_answer = new TextBox();
_answer.ID = "userAnswer";

_button = new Button();
_button.ID = "Button";
_button.Text = rm.GetString("Verify");
_button.OnClientClick = "return CheckAnswer();";

Controls.Add(_firstLabel);
Controls.Add(new LiteralControl(" + "));
Controls.Add(_secondLabel);
Controls.Add(new LiteralControl(" = "));
Controls.Add(_answer);
Controls.Add(_button);
}
}
}

vb

Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Resources

Public Class ClientVerification
Inherits Control

Private _button As Button
Private _firstLabel As Label
Private _secondLabel As Label
Private _answer As TextBox
Private _firstInt As Int32
Private _secondInt As Int32


Protected Overrides Sub CreateChildControls()
Dim random = New Random()
_firstInt = random.Next(0, 20)
_secondInt = random.Next(0, 20)

Dim rm = New ResourceManager("LocalizingScriptResources.VerificationResources", Me.GetType().Assembly)
Controls.Clear()

_firstLabel = New Label()
_firstLabel.ID = "firstNumber"
_firstLabel.Text = _firstInt.ToString()

_secondLabel = New Label()
_secondLabel.ID = "secondNumber"
_secondLabel.Text = _secondInt.ToString()

_answer = New TextBox()
_answer.ID = "userAnswer"

_button = New Button()
_button.ID = "Button"
_button.Text = rm.GetString("Verify")
_button.OnClientClick = "return CheckAnswer();"

Controls.Add(_firstLabel)
Controls.Add(New LiteralControl(" + "))
Controls.Add(_secondLabel)
Controls.Add(New LiteralControl(" = "))
Controls.Add(_answer)
Controls.Add(_button)
End Sub

End Class

The code creates a custom ASP.NET control. It contains two Label controls, a TextBox control, and a Button control. The code displays two randomly generated integers and provides a text box for an answer. When the button is clicked, the CheckAnswer function is called.
8.

Add a resources file to the project and name it VerificationResources.resx.
9.

Add a string resource named Correct with a value of "Yes, your answer is correct."
10.

Add a string resource named Incorrect with a value of "No, your answer is incorrect."
11.

Add a string resource named Verify with a value of "Verify Answer".

This resource is not retrieved by using client script. Instead, it is used to set to the Text property of the Button control when the button is created.
12.

Save and close the VerificationResources.resx file.
13.

Add a resources file named VerificationResources.it.resx to the project.

This file will contain resource strings in Italian.
14.

Add a string resource named Correct with a value of "Si, la risposta e’ corretta."
15.

Add a string resource named Incorrect with a value of "No, la risposta e’ sbagliata."
16.

Add a string resource named Verify with a value of "Verificare la risposta".

As with the "Verify" resource that you created in English, this resource is not retrieved by using client script. Instead, it is used to set the Text property of the Button control when the button is created.
17.

Save and close the VerificationResources.it.resx file.
18.

Add the following line to the AssemblyInfo file. You can specify any name for the type name in the ScriptResourceAttribute attribute, but it must match the type name that is used in the client script. In this example, it is set to Answer.
cs

[assembly: System.Web.UI.WebResource("LocalizingScriptResources.CheckAnswer.js", "application/x-javascript")]
[assembly: System.Web.UI.ScriptResource("LocalizingScriptResources.CheckAnswer.js", "LocalizingScriptResources.VerificationResources", "Answer")]

vb




note

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.

The WebResource definition must include the default namespace of the assembly and the name of the .js file. The ScriptResource definition does not include the file name extension or the localized .resx files.
19.

Build the project.

When compilation finishes, you will have an assembly named LocalizingScriptResources.dll. The JavaScript code in the CheckAnswer.js file and the resources in the two .resx files are embedded in this assembly as resources.

You will also have an assembly named LocalizingScriptResources.resources.dll (a satellite assembly) that contains the Italian resources for server code.

Referencing the Embedded Script and Resources

You can now use the assembly in an AJAX-enabled ASP.NET Web site. You will be able to read the .js file and the resource values in client script.
note

Although you can create the class library project and the Web site in the same Visual Studio solution, in this tutorial it is not assumed that you are doing this. Having the projects in separate solutions emulates how a control developer and a page developer would work separately. However, for convenience you can create both projects in the same solution and make small adjustments to procedures in the tutorial.
To reference the embedded script and resources

1.

In Visual Studio, create a new AJAX-enabled Web site.
2.

Add a Bin folder under the Web site root.
3.

Add the LocalizingScriptResources.dll assembly from the class library project to the Bin folder.
note

If you created the class library project and the Web site in the same Visual Studio solution, you can add a reference from the class library project to the Web site. For details, see How to: Add a Reference to a Visual Studio Project in a Web Site.
4.

Create a folder in the Bin folder and give it the name it (for Italian).
5.

Add the LocalizingScriptResources.resources.dll satellite assembly from the it folder in the LocalizingScriptResources project to the it folder in the Web site.
6.

Add a new ASP.NET Web page to the project.
7.

Replace the code in the page with the following code:
cs

<%@ Page Language="C#" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources" Assembly="LocalizingScriptResources" %>




























vb

<%@ Page Language="VB" AutoEventWireup="true" UICulture="auto" Culture="auto" %>
<%@ Register TagPrefix="Samples" Namespace="LocalizingScriptResources" Assembly="LocalizingScriptResources" %>




























The control that you created in the LocalizingScriptResources project is included on the page. This control displays two numbers for the user to add and a TextBox control for the user to enter an answer. It also displays a button that calls the script in the CheckAnswer function when the button is clicked. The CheckAnswer function runs in the browser and displays a localized message that states whether the answer is correct.

You must set the EnableScriptLocalization property of the ScriptManager object to true to enable the ScriptManager control to retrieve localized resources. You must also set the culture and UI culture to "auto" to display the strings that are based on the browser's settings.

The page contains a DropDownList control that you can use to change the language settings without changing the settings in the browser. When the SelectedIndex property of the DropDownList control changes, the CurrentUICulture property of the CurrentThread instance is set to the value that you have selected.
8.

Run the project.

You will see an addition problem with two randomly generated numbers and a TextBox control for entering an answer. When you enter an answer and click the Verify Answer button, you see the response in a message window that tells you whether the answer is correct. By default, the response will be returned in English.

However, if you have set Italian as your preferred language in the browser, the answer will be in Italian. You can change the language for the response by selecting a language in the DropDownList control or by changing the preferred language in the browser.

Review

This tutorial introduced the concept of embedding a JavaScript file as a resource in an assembly and of including localized strings. The embedded script file can be referenced and accessed in a Web application that contains the assembly. The localized strings will be displayed based on the language setting in the browser or on the language provided by the user.

Debugging and Tracing
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:

*

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








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

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

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

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.

Web Services
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

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

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:

*

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.
ACSC Communication
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.
ACSC Client Architecture
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 browser’s 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.
*

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

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

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

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 client-server 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

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.
ACSC Server Architecture
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.
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
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 Class -


Provides the functionality for interfacing with the network to perform Web requests.

WebRequestManager Class


Manages the flow of network requests from the WebRequest class to 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 Class


Provides serialization and deserialization functionality.

AuthenticationService Class


Provides the client proxy class for the authentication service.

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

Calling Web Services from Client Script in ASP.NET AJAX
Introduction

This topic explains how to use to call a Web service from ECMAScript (JavaScript). To enable your application to call ASP.NET AJAX Web services by using client script, the server asynchronous communication layer automatically generates JavaScript proxy classes. A proxy class is generated for each Web service for which an element is included under the control in the page.

For more information, see Exposing Web Services to Client Script.

To call a method of the Web service, you call the corresponding method of the generated JavaScript proxy class. The proxy class in turn communicates with the Web service.
Calling Web Service Methods

Calling a Web service method from script is asynchronous. To get a return value or to determine when the request has returned, you must provide a succeeded callback function. The callback function is invoked when the request has finished successfully, and it contains the return value (if any) from the Web method call. You can also provide a failed callback function to handle errors. Additionally, you can pass user context information to use in the callback functions.

The following example shows how to make the following types of Web service calls:

*

Calling a Web service that has no return value.
*

Calling a Web service that returns a value.
*

Calling a Web service method that takes parameters.
*

Calling a Web service method by using the HTTP GET verb.
*

Calling a Web service method that returns an XmlDocument object.

Run View
Specifying Callback Functions as Default Properties

In the previous examples, calls to Web service methods are made by using the proxy class. Information about the succeeded callback function, the failed callback function, and the user context is passed by using additional parameters in the call.

As an alternative, you can specify a succeeded callback function, a failed callback function, and user context as default properties for the class. Your script can then invoke the Web service methods of the proxy class without passing these values as parameters in the call. This simplifies the syntax of calling Web service methods.

The following example shows how to set default properties on the Web service proxy class, and then call a Web service method.

MyNameSpace.MyService.set_defaultSucceededCallback(SucceededCallback);
MyNameSpace.MyService.set_defaultFailedCallback(FailedCallback);
MyNameSpace.MyService.set_defaultUserContext("my context");
MyNameSpace.MyService.myServiceMethod(param1, param2);

Setting Callback Functions as Properties of Proxy Class Instances

You can also create instances of the generated proxy class. In that case, you can specify a succeeded callback function, a failed callback function, and user context as default properties for each instance. As with calling the generated proxy class, you can then use the proxy class instances to call Web service methods without passing these values as parameters in the call.

You typically create proxy-class instances when you want to make multiple calls to methods of the Web service and use different default property values for each instance. For example, you can specify different callback functions for each instance. By using different callback functions, you can process the returned data in different ways based on your application needs and on the nature of the returned data.

The following example shows how to create an instance of a proxy class, set its default properties, and call the related Web service method:

var myServiceProxy = new MyNameSpace.MyService();
myServiceProxy.set_defaultSucceededCallback(SuccededCallback);
myServiceProxy.set_defaultFailedCallback(FailedCallback);
MyNameSpce.MyService.set_defaultUserContext("my context");
myServiceProxy.myServiceMethod(param1, param2);

For more information, see Generated Proxy Classes.
Handling Errors in Web Service Method Calls

The following example shows how to handle errors that are raised by Web service methods. In order to catch errors, you must provide a failed callback function that accepts a single parameter. This parameter will contain the error object sent by the Web service.

The following example show how to provide a failed callback function that is called if an error occurs during a Web service method call.
Run View
Calling a Single Callback Function from Multiple Web Service Methods

You can provide a single succeeded callback function that is invoked from multiple Web service method calls. In order for the function to distinguish between callers, you can pass user context to it, or you can test for the name of the calling method. The user context and the calling method name are both available in the callback function, as shown in the following example:
Run View
Passing and Returning Complex Types

If the Web service method returns a complex type, the succeeded callback function receives a return value in the form of a JavaScript object that corresponds to the server type. The following example shows a Web service method that returns a complex type.
Run View

The following example shows how to call Web service methods that have parameters that correspond to complex types. Proxy classes for the types will be automatically generated. This enables client script to create instances of the type to pass as parameters to the method call.
Run View
Passing Parameters Typed as Generics or Arrays

A Web service method might support parameters or a return value that are typed as generics or arrays of lists of type T. In that case, ASP.NET AJAX automatically generates proxy classes for the type T for use with client script. However if a generic type takes more than one type argument, such as Dictionary>, ASP.NET AJAX does not generate proxy classes for the types.

For ASP.NET AJAX to generate a proxy class for the type T, the Web service class that uses the type must be qualified with the GenerateScriptTypeAttribute attribute for the type T.

The following example shows how to call a Web service method from client script when the parameters are typed as generics or arrays.
Run View
Passing Parameters Typed as Enumerators

An enumerator type can be accessed by using the automatically generated proxy class.
note

You cannot access enumerators by using instances of the generated proxy class.

The following example shows how to call a Web service method from client script when the parameters are typed as enumerators.
Run View