Professional Documents
Culture Documents
ASP NET AJAX Intro
ASP NET AJAX Intro
ASP NET AJAX Intro
Components
• Client components enable rich behaviors in the browser without postbacks.
Components fall into three categories:
- Components, which are non-visual objects that encapsulate code, such as a
timer object.
- Behaviors, which extend the basic behavior of existing DOM elements.
- Controls, which represent a new DOM element that has custom behavior.
• The type of component that you use depends on the type of client behavior you
want. For example, a watermark for an existing text box can be created by using a
behavior that is attached to the text box.
Browser Compatibility
• The browser compatibility layer provides AJAX scripting compatibility for the
most frequently used browsers (including Microsoft Internet Explorer, Mozilla
Firefox, and Apple Safari). This enables you to write the same script regardless of
which supported browser you are targeting.
Networking
• The networking layer handles communication between script in the browser and
Web-based services and applications. It also manages asynchronous remote
method calls. In many common scenarios, such as partial-page updates that use
the UpdatePanel
• The networking layer also provides support for accessing server-based forms
authentication, role information, and profile information in client script. This
support is also available to Web applications that are not created by using
ASP.NET, as long as the application has access to the Microsoft AJAX Library.
Core Services
• The AJAX client-script libraries in ASP.NET consist of JavaScript (.js) files that
provide features for object-oriented development. The object-oriented features
included in the ASP.NET AJAX client-script libraries enable a high level of
consistency and modularity in client scripting. The following core services are
part of the client architecture:
• Object-oriented extensions to JavaScript, such as classes, namespaces, event
handling, inheritance, data types, and object serialization.
• A base class library, which includes components such as string builders and
extended error handling.
• Support for JavaScript libraries that are either embedded in an assembly or are
provided as standalone JavaScript (.js) files. Embedding JavaScript libraries in an
assembly can make it easier to deploy applications and can help solve versioning
issues.
Globalization
• The AJAX server and client architecture in ASP.NET provides a model for
localizing and globalizing client script. This enables you to design applications
that use a single code base to provide UI for many locales (languages and
cultures). For example, the AJAX architecture enables JavaScript code to format
Date or Number objects automatically according to culture settings of the user's
browser, without requiring a postback to the server.
Script Support
• AJAX features in ASP.NET are implemented by using supporting scripts that are
sent from the server to the client. Depending on what AJAX features that you
enable, different scripts are sent to the browser.
• You can also create custom client script for your ASP.NET applications. In that
case, you can also use AJAX features to manage your custom script as static .js
files (on disk) or as .js files embedded as resources in an assembly.
• ASP.NET AJAX features include a model for release and debug modes. Release
mode provides error checking and exception handling that is optimized for
performance, with minimized script size. Debug mode provides more robust
debugging features, such as type and argument checking. ASP.NET runs the
debug versions when the application is in debug mode. This enables you to throw
exceptions in debug scripts while minimizing the size of release code.
• Script support for AJAX in ASP.NET is used to provide two important features:
• The Microsoft AJAX Library, which is a type system and a set of JavaScript
extensions that provide namespaces, inheritance, interfaces, enumerations,
reflection, and additional features
• Partial-page rendering, which updates regions of the page by using an
asynchronous postback.
Localization
• The ASP.NET AJAX architecture builds on the foundation of the ASP.NET 2.0
localization model. It provides additional support for localized .js files that are
embedded in an assembly or that are provided on disk. ASP.NET can serve
localized client scripts and resources automatically for specific languages and
regions.
Web Services
• With AJAX functionality in an ASP.NET Web page, you can use client script to
call both ASP.NET Web services (.asmx) and Windows Communication
Foundation (WCF) services (.svc). The required script references are
automatically added to the page, and they in turn automatically generate the Web
service proxy classes that you use from client script to call the Web service.
• You can also access ASP.NET Web services without using ASP.NET AJAX server
controls (for example, if you are using a different Web development
environment). To do so, in the page you can manually include references to the
Microsoft AJAX Library, to script files, and to the Web service itself. At run time,
ASP.NET generates the proxy classes that you can use to call the services
Application Services
• Application services in ASP.NET are built-in Web services that are based on
ASP.NET forms authentication, roles, and user profiles. These services can be
called by client script in an AJAX-enabled Web page, by a Windows client
application, or by a WCF-compatible client.
Server Controls
• ASP.NET AJAX server controls consist of server and client code that integrate to
produce rich client behavior. When you add an AJAX control to an ASP.NET Web
page, the page automatically sends supporting client script to the browser for
AJAX functionality. You can provide additional client code to customize the
functionality of a control, but this is not required.
The following list describes the most frequently used ASP.NET AJAX server controls.
ScriptManager
• Manages script resources for client components, partial-page rendering,
localization, globalization, and custom user scripts.
• The ScriptManager control is required in order to use the UpdatePanel ,
UpdateProgress and Timer controls.
UpdatePanel
• Enables you to refresh selected parts of the page, instead of refreshing the whole
page by using a synchronous postback.
UpdateProgress
• Provides status information about partial-page updates in UpdatePanel controls.
Timer
• Performs postbacks at defined intervals. You can use the Timer control to post the
whole page, or use it together with the UpdatePanel control to perform partial-
page updates at a defined interval.
You can also create custom ASP.NET server controls that include AJAX client behaviors.
Custom controls that enhance the capabilities of other ASP.NET Web controls are
referred to as extender controls.
The current code will look like ordinary ASP.NET, with a few new web controls. The
markup: Using ASP.NET AJAX Enabled Website
Nothing fancy here, really. When we create the new website, a Default.aspx file is created
for us, including the ScriptManager control.
ScriptManager control
The ScriptManager control manages client script for AJAX-enabled ASP.NET Web
pages. By default, the ScriptManager control registers the script for the Microsoft AJAX
Library with the page. This enables client script to use the type system extensions and to
support features such as partial-page rendering and Web-service calls.
Scenarios
You must use a ScriptManager control on a page to enable the following AJAX features
of ASP.NET:
• Client-script functionality of the Microsoft AJAX Library, and any custom script
that you want to send to the browser. For more information, see Creating Custom
Client Script by Using the Microsoft AJAX Library.
• Partial-page rendering, which enables regions on the page to be independently
refreshed without a postback. The ASP.NET UpdatePanel, UpdateProgress, and
Timer controls require a ScriptManager control in order to support partial-page
rendering.
• JavaScript proxy classes for Web services, which enable you to use client script to
access Web services and specially marked methods in ASP.NET pages. It does this
by exposing the Web services and page methods as strongly typed objects.
• JavaScript classes to access ASP.NET authentication, profile, and roles
application services.
Background
• When a page contains one or more UpdatePanel controls, the ScriptManager
control manages partial-page rendering in the browser. The control interacts with
the page life cycle to update the parts of the page that are inside UpdatePanel
controls. For more information, see Partial-Page Rendering Overview.
• The EnablePartialRendering property of the ScriptManager control determines
whether a page participates in partial-page updates. By default, the
EnablePartialRendering property is true. Therefore, by default partial-page
rendering is enabled when you add a ScriptManager control to the page. For
information about how to use the UpdatePanel control with the ScriptManager
control, see Introduction to the UpdatePanel Control and Creating a Simple
ASP.NET Page with Multiple UpdatePanel Controls.
This control should be used on every page where you wish to use AJAX, since it creates
basic AJAX support on your page, besides giving some more advanced possibilities,
which we will look into later on. After the manager, we have one of the most used
controls when working with AJAX, the UpdatePanel. This control allows you to wrap
markup which you would like to allow to be partially updated, that is, updated without
causing a real postback to the server. More about the UpdatePanel in a coming chapter.
Besides those two controls, everything else is standard controls, with no modifications
that would indicate alternate behavior.
Try running the example site, and click the button. The label will be updated with our
usual Hello world text, and a random number. Try repeatedly clicking the button, and you
will see the label get a new number each time. Notice the wonderful absence of a
blinking window and a running status bar - everything is done without updating anything
but the label! We've just created our first AJAX enabled page. If you wish to see how this
page would work without AJAX, try setting the "enablepartialrendering" of the
ScriptManager to false like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" enablepartialrendering="false"
/>
This will disallow the use of partial rendering on the page, and show you how it would
work without AJAX.
UpdatePanel control
ASP.NET UpdatePanel controls enable you to build rich, client-centric Web applications.
By using UpdatePanel controls, you can refresh selected parts of the page instead of
refreshing the whole page with a postback. This is referred to as performing a partial-
page update. An ASP.NET Web page that contains a ScriptManager control and one or
more UpdatePanel controls can automatically participate in partial-page updates, without
custom client script.
Scenarios
• The UpdatePanel control is a server control that helps you develop Web pages
with complex client behavior that makes a Web page appear more interactive to
the end user. Writing code that coordinates between server and client to update
only specified parts of a Web page usually requires in-depth knowledge of
ECMAScript (JavaScript).
• However, by using the UpdatePanel control, you can enable a Web page to
participate in partial-page updates without writing any client script. If you want,
you can add custom client script to enhance the client user experience. When you
use an UpdatePanel control, the page behavior is browser independent and can
potentially reduce the amount of data that is transferred between client and server.
Background
• UpdatePanel controls work by specifying regions of a page that can be updated
without refreshing the whole page. This process is coordinated by the
ScriptManager server control and the client PageRequestManager class.
• When partial-page updates are enabled, controls can asynchronously post to the
server. An asynchronous postback behaves like a regular postback in that the
resulting server page executes the complete page and control life cycle.
• However, with an asynchronous postback, page updates are limited to regions of
the page that are enclosed in UpdatePanel controls and that are marked to be
updated. The server sends HTML markup for only the affected elements to the
browser. In the browser, the client PageRequestManager class performs
Document Object Model (DOM) manipulation to replace existing HTML with
updated markup.
When you are using asynchronous postbacks or using the XMLHTTPRequest object, a
postback error can occur if the URL contains a double-byte character. You can resolve this
problem by including a <base href="url"/> element in the head element of the page, where
the href attribute is set to the URL-encoded string that references the page. You can add
this element added dynamically in server code.
The following illustration shows a page that is loaded for the first time, and a subsequent
asynchronous postback that refreshes the content of an UpdatePanel control.
Partial-page rendering overview
The UpdatePanel control requires a ScriptManager control in the Web page. By default,
partial-page updates are enabled because the default value of the EnablePartialRendering
property of the ScriptManager control is true.
So, what's this example all about? Try running it, and click the two buttons. You will
notice that then first button updates only the first datestamp, while the second button
updates both. Why? We have set the Panels to update conditionally, which means that
their content is only updated if something insides them causes a postback, or if one of the
defined triggers are fired. As you can see, the first UpdatePanel carries a trigger which
references the second button. This will ensure that the first panel is updated even when a
control on a different UpdatePanel is used.
The AsyncPostBackTrigger tag is pretty simple - it only takes two attributes, the
controlid, a reference to the control which can trigger it, and the eventname, which tells
which eventtype can cause the trigger to fire. If you wish for the content of a
UpdatePanel to be updated no matter what, you may change the updatemode property to
Always.
In general, you should only have UpdatePanels around areas where you wish to do partial
updates. Don't wrap your entire page within an UpdatePanel, and don't be afraid to use
several panels, since this will give you more control of which areas update and when they
do it.
UpdateProgress control
The UpdateProgress control provides status information about partial-page updates in
UpdatePanel controls. You can customize the default content and the layout of the
UpdateProgress control. To prevent flashing when a partial-page update is very fast, you
can specify a delay before the UpdateProgress control is displayed.
Scenarios
• The UpdateProgress control helps you design a more intuitive UI when a Web
page contains one or more UpdatePanel controls for partial-page rendering. If a
partial-page update is slow, you can use the UpdateProgress control to provide
visual feedback about the status of the update. You can put multiple controls on a
page, each associated with a different UpdatePanel control. Alternatively, you can
use one UpdateProgress control and associate it with all UpdatePanel controls on
the page.
Background
• The UpdateProgress control renders a <div> element that is displayed or hidden
depending on whether an associated UpdatePanel control has caused an
asynchronous postback. For initial page rendering and for synchronous postbacks,
the UpdateProgress control is not displayed.
One of the problems with Ajax, is the fact that since it's asynchronus and in the
background, the browser will not show you any status. With fast servers and fast
methods, this is not a big problem, but whenever you have a method which takes up a bit
of time, the user is very likely to get impatient. Fortunately, ASP.NET AJAX solves this
problem for us as well, with a nice control called UpdateProgress. It will use your own
template to show that an asynchronus method is working. Have a look at the following
example, which will show the control in action. It will be explained afterwards.
You can have multiple UpdateProgress controls on the page, and by using the
AssociatedUpdatePanelID property, you can make sure that the UpdateProgress is only
shown when a certain UpdatePanel is updated.
The DynamicLayout property is nice to know as well. It tells whether or not the page
should reserve space for your progress control. If it's set to true, which is the default, the
space is dynamic, hence it's not reserved, but taken when the control is shown. If you
wish to reserve the space, set this property to false. To see the difference, add the property
to our example and change it back and forth.
If some of your postbacks are fast, the UpdateProgress will only be shown for a very
short amount of time, resulting in a blinking behavior, which may confuse your users. For
that reason, you may specify a minimum amount of time to occur before showing the
progress control. This can be done with the DisplayAfter attribute. Specify a number of
milliseconds to elapse before showing the progress control, e.g. 2000 if you wish to wait
for 2 seconds.
Timer control
Timer controls allow you to do postbacks at certain intervals. If used together with
UpdatePanels, which is the most common approach, it allows for timed partial updates of
your page, but it can be used for posting back the entire page as well. In this chapter we
will focus on using timers with UpdatePanels, so if you haven't already read the chapter
on UpdatePanels, please do so now.
Here is a small example of using the Timer control. It simply updates a timestamp every
5 seconds.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Timers</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000"
ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
We only have a single CodeBehind function, which you should add to your CodeBehind
file:
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
}
This is all very simple. We have a normal UpdatePanel, which carries a Trigger reference
to our new Timer control. This means that the panel is updated when the Timer "ticks",
that is, fires the Tick event. The Timer control uses the interval attribute to define the
number of milliseconds to occur before firing the Tick event. As you can see from our
CodeBehind code listing, we just update the DateStampLabel each time the Timer fires.
This could be done more efficient with a simple piece of JavaScript, which updates the
time on the clientside instead of involving the server. The example is only used to
demonstrate the potential of the Timer control.
Another approach is including the Timer inside the UpdatePanel. Doing so would save us
from defining a trigger, but you should be aware of the fact that the behavior will be
different, depending on whether you have the Timer inside or outside an UpdatePanel.
When a Timer is inside an UpdatePanel, the Timer is not re-constructed until the
UpdatePanel is fully updated. That means that if you have a Timer with an interval of 60
seconds, and the update takes 5 seconds, the next event won't be fired 60 seconds after
the previous, but 65 seconds after. On the other hand, if the Timer is outside the
UpdatePanel, the user will only look at the content of the panel for 55 seconds before it's
updated again.
You should always remember that even though partial updates are not as heavy on the
server as real postbacks, the server is still contacted, and when using timers, you may get
a lot of partial postbacks, which can slow things down. Always use as high intervals as
possible, and consider if contacting the server is really necessary or not.
• A Microsoft ASP.NET AJAX page raises the same server life-cycle events as an
ASP.NET 2.0 Web page and also raises client life-cycle events. The client events
enable you to customize the UI for both postbacks and for asynchronous
postbacks (partial-page updates). The client events also help you manage custom
script components during the lifetime of the page in the browser.
• The client events are raised by classes in the Microsoft AJAX Library. These
classes are automatically instantiated when a page contains ASP.NET AJAX
server controls. The client classes provide APIs that enable you to bind to events
and to provide handlers for those events. Because the Microsoft AJAX Library is
browser independent, the code you write for your handlers works the same in all
supported browsers.
• The key event for initial requests (GET requests) and synchronous postbacks is
the load event of the Application instance. When script in a load event handler
runs, all scripts and components have been loaded and are available. When
partial-page rendering with UpdatePanel controls is enabled, the key client events
are the events of the PageRequestManager class. These events enable you to
handle many common scenarios. These include the ability to cancel postbacks, to
give precedence to one postback over another, and to animate UpdatePanel
controls when their content is refreshed.
• Client events are useful whether you are creating pages or writing components. If
you are a page developer, you can provide custom script that is called when the
page loads and unloads in the browser.
Client Classes
• The two main Microsoft AJAX Library classes that raise events during the client
life cycle of an ASP.NET AJAX Web page are the Application and
PageRequestManager classes.
• The Application class is instantiated in the browser when the page contains a
ScriptManager control. The Application class resembles the Page server control,
which derives from the Control class, but provides additional functionality for
raising server events. Similarly, the Application class derives from the
Sys.Component class, but raises client life-cycle events that you can handle.
• If a page contains a ScriptManager control and one or more UpdatePanel controls,
the page can perform partial-page updates (if partial-page rendering is enabled
and supported in the browser). In that case, an instance of the
PageRequestManager class is automatically available in the browser. The
PageRequestManager class raises client events that are specific to asynchronous
postbacks.
Initial Request
During the initial request for the page, a limited number of client events are raised.
Assume the following scenario for the initial request:
• The page contains a ScriptManager control, and the control's
SupportsPartialRendering and EnablePartialRendering property are both true.
• The request is a GET request.
• A response from the server is returned successfully.
The following client events occur, in this order:
• The initial request is sent to the server.
• The response is received by the client.
• The Application instance raises the init event.
• The Application instance raises the load event.
• The init event of the Application instance is raised only one time for the life of the
page in the browser. It is not raised for subsequent asynchronous postbacks.
During an initial request, no PageRequestManager events are raised.
Asynchronous Postback
An asynchronous postback sends some page data to the server, receives a response, and
updates a part of the page. Assume the following scenario for an asynchronous postback:
• The page contains a ScriptManager control, and the control's
SupportsPartialRendering and EnablePartialRendering properties are both true.
• The page contains an UpdatePanel control, and the control's ChildrenAsTriggers
property is true.
• A button inside the UpdatePanel control initiates an asynchronous postback.
• A response from the server is returned successfully.
The following client events occur, in this order:
• The button inside the UpdatePanel is clicked, which initiates an asynchronous
postback.
• The PageRequestManager instance raises the initializeRequest event.
• The PageRequestManager instance raises the beginRequest event.
• The request is sent to the server.
• The response is received by the client.
• The PageRequestManager instance raises the pageLoading event.
• The PageRequestManager instance raises the pageLoaded event.
• The Application instance raises the load event.
• The PageRequestManager instance raises the endRequest event.
• Note that the load event of the Application instance is raised after the
PageRequestManagerpageLoaded event and before its endRequest event.
The default behavior of asynchronous postbacks is that the most recent asynchronous
postback takes precedence. If two asynchronous postbacks occur in sequence, and if the
first postback is still being processed in the browser, the first postback is canceled. If the
first postback has been sent to the server, the server processes the second request when it
arrives and does not return the first request.