ASP.NET2.0 AJAX
For Richer, Dynamic and Responsive Web
Applications
Tableofof
Contents
Table
Contents
•
What is AJAX?
•
What is ASP.NET2.0 AJAX?
•
Why use ASP.NET2.0 AJAX?
•
The Client and Server Pieces of ASP.NETAJAX
•
Installing ASP.NET AJAX
•
AJAX Libraries for ASP.NET
•
ScriptManager
•
Partial Page Updates
 UpdatePanel Control
 UpdateProgress Control
 Timer Control
Tableofof
Contents
Table
Contents
•
ASP.NET AJAX Client Library
 AJAX JavaScript Extensions
 AJAX Base Class Library
•
ASP.NET AJAX Networking
 XMLHttpRequest Object
 Data Communication
 JSON
•
Calling Web Services from Client Script
•
Rich AJAX Toolkit Controls & ASP.NET Futures CTP
•
Server and Client Reference
Whatis is
AJAX?
What
AJAX?
Ajax (asynchronous JavaScript and XML), or AJAX, is a group of interrelated web development
techniques used for creating interactive web applications or rich Internet applications
Google Suggest provides users with a list
Google Maps covers the entire planet,
of options based on keyed-in characters
though with varying degrees of granularity.
without refreshing the page.
It offers satellite pictures as well as the
usual abstract map representations.
Historyofof
AJAX?
History
AJAX?
Jesse James Garrett, co-founder and president of Adaptive
Path in 2005, coined the term Ajax and defined the
concepts behind it.
Examples
•
Flickr - A Yahoo! Company
 Flickr is a photo storage and display program
that uses AJAX.
•
Gmail - Google
 Gmail is an AJAX powered email system.
AJAXTechnology?
Technology?
AJAX
It refers specifically to these
technologies:
•
XHTML and CSS for
presentation
•
The Document Object
Model for dynamic
display and interaction
with data
•
XML and XSLT for the
interchange and
manipulation of data,
respectively
•
The XMLHttpRequest
object for asynchronous
communication
•
JavaScript to bring these
technologies together
Whatis is
ASP.NET
AJAX?
What
ASP.NET
AJAX?
ASP.NET AJAX is the name of Microsoft’s AJAX solution, and it refers to a set of client and
server technologies that focus on improving web development with Visual Studio
Whyuse
use
ASP.NET
AJAX?
Why
ASP.NET
AJAX?
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.
TheClient
Client
and
Server
pieces
of ASP.NET
The
and
Server
pieces
of ASP.NET
AJAX AJAX
ASP.NET is built on top of the Microsoft
Internet Information Services (IIS) web
server.
ASP.NET AJAX builds on top of that and the
web services it includes. The Microsoft AJAX
Library runs in the browser to manipulate the
DOM, communicate asynchronously with the
web server, and take advantage of ASP.NET
services.
TheClient
Client
and
Server
pieces
of ASP.NET
The
and
Server
pieces
of ASP.NET
AJAX AJAX
Microsoft AJAX Library
It is a JavaScript library that works on a variety of browsers and serves to simplify JavaScript
development.
It is a type system and set of class libraries that simplify writing JavaScript to enhance the user
experience, manipulate the DOM, and communicate with the web server
ASP.NET 2.0 AJAX Extensions
These extensions build on top of the ASP.NET classes and controls and leverage the Microsoft
AJAX Library sent to the browser.
•
They make it easy to quickly take advantage of AJAX technologies by providing a set of
server controls.
•
Through a set of standard web services, ASP.NET AJAX is also able to leverage serverbased application services such as authentication and user profile storage
Installing
ASP.NET
AJAX
Installing
ASP.NET
AJAX
ASP.NET AJAX includes
•
Microsoft ASP.NET 2.0 AJAX Extensions, which is a server framework
•
The Microsoft AJAX Library, which consists of client script that runs on the browser.
To install Microsoft ASP.NET AJAX
•
Download the ASPAJAXExtSetup.msi installation package from the ASP.NET AJAX
Downloads Web site.
•
To add the ASP.NET AJAX Control Toolkit, download and install it from ASP.NET AJAX
Control Toolkit Web site.
If you have Microsoft Visual Studio 2005 installed on your computer, the installation process
installs templates for AJAX-enabled Web site projects.
It also installs an assembly (AJAXExtensionToolbox.dll) that extends the Visual Studio toolbox
AJAXLibraries
Libraries
ASP.NET
AJAX
forfor
ASP.NET
Ajax.NET Professional: Michael Schwartz developed Ajax.NET Professional as a tool primarily
used to simplify the data transport mechanism that enables a client JavaScript routine to
communicate with a server program.
Anthem.NET: Anthem.NET is a SourceForge project where users are able to download the
sources to the project. It targets ASP.NET 1.1 and ASP.NET 2.0. It has a set of server
controls that use their underlying JavaScript library to communicate with the server
DoJo: It is a client-side library for AJAX development without ties to any server technology.
DoJo has a type system for JavaScript and a function for binding script to events from
JavaScript objects or DHTML elements. One of its strengths is rich support for dynamic
script loading.
AJAXLibraries
Libraries
ASP.NET
AJAX
forfor
ASP.NET
Prototype: It has a type system for scripting in a more object-oriented way. Prototype
provides networking functionality and a method for automatically updating an HTML
element with the results of an HTTP request when given a URL.
Script.aculo.us:Script.aculo.us is built on top of the Prototype library. It includes functionality
for adding drag-and-drop support to an application. It has a lot of effects code for fading,
shrinking, moving, and otherwise animating DOM elements. Script.aculo.us also has a
slider control and a library for manipulating lists of elements.
Rico: The Rico library also builds on top of the Prototype system. It has support for adding
drag-and-drop behavior to browser DOM elements. It also has some controls to bind
JavaScript objects to DOM elements for manipulating data. Rico has constructs for
revealing and hiding portions of a page using an accordion style. It also has animation,
sizing, and fading effects prebuilt for easier use.
ScriptManager
Script
Mangager
Any AJAX library needs a component or a tool that makes some JavaScript code available on
the client. This script code represents the client infrastructure necessary for the library to
work .
AJAX libraries tend to offer a server-side, often parameterless, component that when dropped
on the page automatically outputs any required scripts. This component is generally known
as the AJAX manager or script manager
In addition to ensuring that the proper script is linked to the page, the script manager typically
•
Enables and supports partial page rendering,
•
Generates proxy code to call remotely into server-side methods and objects,
•
Sets up auxiliary services.
PartialPage
Page
Updates
Partial
Updates
Partial rendering divides the page into independent regions, each of which controls its own
postbacks and refreshes without causing or requiring a full page update. This is desirable
when only a portion of the page needs to change during a postback.
•
Partial updates reduce screen flickering and allows to create more interactive Web
applications
•
Partial rendering requires a ScriptManager control in the page. It is essential that the
EnablePartialRendering property on the manager be set to true—which is the default case.
PartialPage
Page
UpdatesUpdate Panel
Panel Control
Partial
Updates
– Update
Control
The UpdatePanel is a container control without any UI of its own.
•
Defined in the System.Web.Extensions assembly, it belongs specifically to the
System.Web.UI namespace. The control class is declared as follows:
public class UpdatePanel : Control{
•
...}
The control has a number of properties to control page updates and also exposes a
clientside object model.
•
When a control within the UpdatePanel triggers a postback, the UpdatePanel intervenes to
initiate the postback asynchronously and update just that portion of the page.
•
At the time the call to the server is made, the name of a JavaScript callback function that
will be called is provided, when the response has been received. That callback function will
receive the results and update various page controls accordingly.
PartialPage
Page
UpdatesUpdate Panel
Panel Control
Partial
Updates
– Update
Control
Partial Page Update is coordinated by the ScriptManager server control and the client
PageRequestManager class.
When partial-page updates are enabled, controls can asynchronously posted to the server.
•
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 UpdatePanel control sends an out-of-band request for fresh markup and then
updates the Document Object Model (DOM) tree when the response is ready.
PartialPage
Page
UpdatesUpdate Panel
Panel Control
-Example
Partial
Updates
– Update
Control
- Example
The Example page has two labels and two buttons that can each cause a postback.
It simply updates the two labels with the current server time. Button1 and
its label are placed inside an UpdatePanel. Actually, they are put in the
ContentTemplate of the UpdatePanel.. The other label and button are left
outside the UpdatePanel
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server" language="C#" >
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
string theTime = DateTime.Now.ToLongTimeString();
for (int i = 0; i < 3; i++) {
theTime += "<br />" + theTime;
}
time1.Text = theTime;
time2.Text = theTime;
}
</script>
PartialPage
Page
UpdatesUpdate Panel
Panel Control
Partial
Updates
– Update
Control
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Basic Update Panel</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Label runat="server" ID="time1"></asp:Label><br /><br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div style="border-style:solid;background-color:gray;">
<asp:Label runat="server" ID="time2"></asp:Label><br />
<asp:Button ID="Button1" runat="server" Text="Inside Button" />
</div><br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Outside Button" />
</div>
</form>
</body>
</html>
PartialPage
Page
UpdatesUpdate Panel
Panel Control
Partial
Updates
– Update
Control
In the code-behind, both labels are assigned
the same time string in the same way.
When the page is first requested, the two
labels show the same time
When the Outside Button is clicked, a
postback occurs and the time is updated for
both of the labels.
When the button inside the UpdatePanel is
clicked, an
asynchronous postback occurs and only the
label inside the UpdatePanel is updated
PartialPage
Page
UpdatesHow
Update
Panel
Control
refreshed?
Partial
Updates
– How
Update
Panel
Control
is is
refreshed?
The property settings of the UpdatePanel control 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.
PartialPage
Page
UpdatesHow
Update
Panel
Control
refreshed?
Partial
Updates
– How
Update
Panel
Control
is is
refreshed?
If the UpdateMode property is set to Conditional, the UpdatePanel control’s content is
updated when one of the following is true:
•
When the postback is caused by a trigger for that UpdatePanel control.
•
When the UpdatePanel control's Update() method is called explicitly.
•
When the UpdatePanel control is nested inside another UpdatePanel control
and the parent panel is updated.
•
When the ChildrenAsTriggers property is set to true and any child control of
the UpdatePanel control causes a postback. Child controls of nested
UpdatePanel controls do not cause an update to the outer UpdatePanel
control unless they are explicitly defined as triggers for the parent panel.
If the ChildrenAsTriggers property is set to false and the UpdateMode property is set to
Always, an exception is thrown. The ChildrenAsTriggers property is intended to
be used only when the UpdateMode property is set to Conditional.
PartialPage
Page
UpdatesUpdate
Panel
Control
–Triggering
Updates
Partial
Updates
–Update
Panel
Control
– Triggering
Updates
By default, any postback control inside an UpdatePanel control causes an asynchronous
postback and refreshes the panel's content.
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.
A trigger's control event is optional. If an event is not specified, the trigger event is the
default event of the control. For example, for the Button control, the default event is the
Click event.
The trigger is defined by using the <asp:AsyncPostBackTrigger> element inside the
<Triggers> element of the UpdatePanel control.
PartialPage
Page
UpdatesUpdate
Panel
Control
–Triggering
Updates
Partial
Updates
–Update
Panel
Control
– Triggering
Updates
UpdatePanels can be nested inside one another. When the outer UpdatePanel is refreshed, the
inner UpdatePanel will also be refreshed.
when the inner UpdatePanel is updated, the outer UpdatePanel is not affected. Even when the
outer UpdatePanel has ChildrenAsTriggers set to true, an asynchronous update of the
inner UpdatePanel will not cause the outer UpdatePanel to be refreshed.
To have controls in a contained UpdatePanel cause a refresh, they have to be set explicitly as
triggers on the outer UpdatePanel.
PartialPage
Page
UpdatesUpdate
Panel
Control
–Triggering
Updates
Example
Partial
Updates
–Update
Panel
Control
– Triggering
Updates
- Example
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Refreshing Update Panel through
triggers</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1"
Text="Refresh Panel"
runat="server" />
<asp:ScriptManager ID="ScriptManager1"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="Button1" />
</Triggers>
<ContentTemplate>
<fieldset>
<legend>UpdatePanel
content</legend>
<%=DateTime.Now.ToString() %>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
PartialPage
Page
UpdatesUpdate
Panel
Control
with
User
Controls
Partial
Updates
–Update
Panel
Control
with
User
Controls
The ScriptManager control will manage partial-page updates for UpdatePanel controls that are
directly on the ASP.NET Web page or inside a user control on the page.
The user controls inside an update panel will be refreshed when the contents of the update
panel are updated.
It is valid to put an UpdatePanel control inside a user control so that the user control supports
partial-page updates. However, in that case, page developers who add the user control
to a page must explicitly add a ScriptManager control in the host Web page.
PartialPage
Page
UpdatesUpdate
Panel
Control
with
User
Controls
Partial
Updates
–Update
Panel
Control
with
User
Controls
Create a UserControl named
WebUserControl.ascx which performs
temperature conversion from Celsuis to
Fahrenheit.
•
Drag and drop a UpdatePanel
Control and place the textbox and
button controls inside it
•
Add a button event handler to
perform the temperature conversion
Create a Web Page ‘UpdateUserControl.aspx’
•
Place a ScriptManager Control in the
page.
•
Drap and drop the user control into
it.
•
Run the Page.
protected void ConvertButton_Click(object
sender, EventArgs e)
{
double a = 1.8 *
double.Parse(CelText.Text) + 32;
FahText.Text = a.ToString();
}
PartialPage
Page
UpdatesPartial
Page
Update
Cycle
Partial
Updates
–TheThe
Partial
Page
Update
LifeLife
Cycle
The page execution Lifecycle is not altered by the partial rendering feature.
The ScriptManager participates in the lifecycle to facilitate the partial page updates. It
coordinates gathering the renderings from the UpdatePanels that need to be refreshed
during an asynchronous post and carrying the hidden fields necessary to make the
following post function correctly.
Controls that modify the ViewState, even if they are not in the UpdatePanel being affected, do
not have to take any special action to ensure the change is available in subsequent
requests.
Event validation, cross page posting, and ASP.NET’s ability to maintain the scroll position all
continue to work when using the UpdatePanel.
PartialPage
Page
UpdatesUpdate
Panel
Caution
and
Complexities
Partial
Updates
–TheThe
Update
Panel
Cautions
and
Complexities
Complex controls that make heavy use of dynamically registered script won’t work correctly
until they are updated to switch from using the ClientScriptManager of ASP.NET 2.0 to
using the ScriptManager included with ASP.NET AJAX.
The ASP.NET Menu and TreeView controls are not fully compatible with the UpdatePanel in the
1.0 release.
The validation controls also register script in a way that is incompatible with the UpdatePanel.
(Disable the client script for the validator controls and then use them in an UpdatePanel)
Web Parts
PartialPage
Page
UpdatesUpdate
Panel
Caution
and
Complexities
Partial
Updates
–TheThe
Update
Panel
Cautions
and
Complexities
The GridView and DetailsView controls already have a feature for using client callbacks to
paging and sorting. It is not enabled by default, but if the feature is enabled, these
controls cannot be used inside an UpdatePanel.
The FileUpload control also can’t submit files as part of an asynchronous postback
The asp:substitution control
The way the ScriptManager extracts the contents needed for the partial page updates in the
1.0 release, calling Response.Write during the execution of an asynchronous postback
will result in an error
Login, PasswordRecovery, ChangePassword, and CreateUserWizard controls whose contents
have not been converted to editable templates.
PartialPage
Page
UpdatesUpdate
Progress
Control
Partial
Updates
–Update
Progress
Control
Microsoft created the UpdateProgress control to make it easy to provide visual
feedback to the user to indicate that the update is being processed. This is
something like a “busy” hourglass cursor in Windows applications.
using System;
using System.Web.UI;
public partial class UpdateProgress : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
System.Threading.Thread.Sleep(4000);
base.OnLoad(e);
string theTime = DateTime.Now.ToLongTimeString();
for(int i = 0; i < 3; i++)
{
theTime += "<br />" + theTime;
time1.Text = theTime;
}
}
}
PartialPage
Page
UpdatesUpdate
Progress
Control
Partial
Updates
–Update
Progress
Control
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Update Progress</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
Some page content<br />
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DynamicLayout="true"
AssociatedUpdatePanelID="UpdatePanel1" >
<ProgressTemplate> Processing… </ProgressTemplate>
</asp:UpdateProgress> More page content<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate> <div style="border-style:solid;background-color:gray;">
<asp:Button ID="Button1" runat="server" Text="Update" /><br /><br />
<asp:Label runat="server" ID="time1"></asp:Label><br /> </div><br />
</ContentTemplate>
</asp:UpdatePanel><br />
</div>
</form>
</body>
</html>
PartialPage
Page
UpdatesUpdate
Progress
Control
Partial
Updates
–Update
Progress
Control
PartialPage
Page
UpdatesTimer
Control
Partial
Updates
–Timer
Control
ASP.NET Ajax introduces the TimerControl which performs postbacks at defined intervals.
Use the Timer control when the following is required:
•
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.
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.
When a postback was initiated by the Timer control, the Timer control raises the Tick event on
the server. An event handler for the Tick event can be created to perform actions when the
page is posted to the server.
PartialPage
Page
UpdatesTimer
Control
Partial
Updates
–Timer
Control
Using TimerControl with UpdatePanel to update the time on a page every five seconds
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Clock</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="SM1" /> <div>
<asp:TimerControl runat="server" ID="Time" Interval="5000" Enabled="true" />
<asp:UpdatePanel runat="server" ID="TimePanel">
<Triggers> <asp:AsyncPostBackTrigger ControlID="Time" EventName="Tick" /> </Triggers>
<ContentTemplate>
<%= DateTime.Now.ToLongTimeString() %>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
ASP.NETAJAX
AJAXClient
Client
Library
ASP.NET
Library
The AJAX Library brings concepts from the .NET Framework to JavaScript running in the
browser, making the server and client coding models a bit more consistent
The AJAX Library has also added a client-side page lifecycle, similar in concept to the ASP.NET
server-side page lifecycle. This addition makes it easy to participate in the processing of the
page, work with partial page rendering, and provide event handlers for user actions.
ASP.NET AJAX Library establishes a page lifecycle for JavaScript code running in the browser
•
The Browser Page Lifecycle
 The pageLoad and pageUnload functions are the primary points to interact with the
browser page lifecycle.
 The pageLoad function is automatically called after the page is initially
retrieved from the web server and some script processing has occurred.
 The pageUnload function is then called whenever a subsequent request is
initiated (for postback, partial page rendering, or even when navigating to a
different application).
 When the page is loaded again, even during partial rendering, the pageLoad
function will again be triggered.
ASP.NETAJAX
AJAXClient
Client
Library
ASP.NET
Library
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Browser Life Cycle</title>
<script type="text/javascript">
function pageLoad(sender, args) {
alert("hello");
}
function pageUnload(sender, args) {
alert("goodbye");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="sm" />
<div>
</div>
</form>
</body>
</html>
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System
ASP.NET
Library
– Type
The Microsoft AJAX Library adds a type system and extensions to JavaScript objects in order to
provide
•
Namespaces
•
Inheritance
•
Interfaces
•
Enumerations
•
Reflection
•
Helpers for strings and arrays.
They enable 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.
The AJAX Library brings classic OOP concepts to JavaScript. It adds namespace support for
grouping functionality. It also provides helpful debugging facilities, a schema for providing
type information, and a means for localizing string and image resources.
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Namespaces
ASP.NET
Library
– Type
: Namespaces
The AJAX Library synthesizes namespaces by creating objects with those names.
Class definitions can be organized logically in just the same way that is organized using C# or
VB.NET.
If separate files are created for different namespaces, it is possible load them conditionally the
same way the Common Language Runtime loads just the assemblies it needs for an
application and does so on demand
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Namespaces
ASP.NET
Library
– Type
: Namespaces
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET AJAX Namespaces</title>
<script type="text/javascript">
function pageLoad(sender, args)
{
Type.registerNamespace('Wrox.ASPAJAX');
alert(Type.isNamespace(Wrox.ASPAJAX)); //displays
var namespaces = Type.getRootNamespaces();
var mystr="";
for(var i = 0, length = namespaces.length; i < length; i++)
{
mystr=mystr+"\n"+namespaces[i].getName();
}
alert(mystr); //displays
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server"
ID="scriptManager1" />
<div> </div>
</form>
</body>
</html>
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class
ASP.NET
Library
– Type
: Class
Classes are reference types. All classes in JavaScript derive from object.
Classes in ASP.NET AJAX helps 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
•
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
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class
ASP.NET
Library
– Type
: Class
The AJAX Library follows the pattern of declaring a function as the class constructor.
JavaScript allows you to modify the prototype of the function directly, which is how the
AJAX Library creates class members.
The class must then be registered so that it can participate in the semantics of the type
system
•
Local members are accessed with a prefix of “this”.
•
The call to registerClass is on the type being registered. The prototype of the base
type in JavaScript has been modified to add type-system support. Once the type is
registered, an instance of it can be created and its members called.
•
The registerClass function actually has three possible parameters: The first one is for
the name of the type, the second is for the base type being extended, and the last is
to specify any interfaces that the class implements.
ASP.NET
Library
– Type
: Class
ASP.NETAJAX
AJAXClient
Client
Library
-TypeSystem
System:
Class
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET AJAX Class</title>
<script type="text/javascript">
function pageLoad(sender, args) {
Type.registerNamespace('Wrox.ASPAJAX.Samples');
Wrox.ASPAJAX.Samples.Album = function(title, artist) {
this._title = title;
this._artist = artist;
}
Wrox.ASPAJAX.Samples.Album.prototype = {
get_title: function () {
return this._title;
},
get_artist: function() {
return this._artist;
}
}
Wrox.ASPAJAX.Samples.Album.registerClass('Wrox.ASPAJAX.Samples');
var anAlbum = new Wrox.ASPAJAX.Samples.Album("Round Room", "Phish ");
alert(anAlbum.get_title());
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" ID="sm" />
</div>
</form>
</body>
</html>
ASP.NET
Library
– Type
System
: Class
- Inheritance
ASP.NETAJAX
AJAXClient
Client
Library
-Type
System:
Class-Inheritance
Inheritance: Instead of modifying a type directly, inherit from it and extend it in
new members by overriding existing ones
In the prototype model, a derived class has full access to the private members of
the parent class. To be precise, in JavaScript the notion of private members is
not the same as in classic OOP.
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class-Inheritance
ASP.NET
Library
– Type
: Class
- Inheritance
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET AJAX Class Inheritance</title>
<script type="text/javascript">
function pageLoad(sender, args)
{
Type.registerNamespace('Wrox.ASPAJAX.Samples');
Wrox.ASPAJAX.Samples.Album = function(title, artist) {
this._title = title;
this._artist = artist;
}
Wrox.ASPAJAX.Samples.Album.prototype = {
get_title: function () {
return this._title;
},
get_artist: function() {
return this._artist;
}
}
Wrox.ASPAJAX.Samples.Album.registerClass('Wrox.ASPAJAX.Samples');
Wrox.ASPAJAX.Samples.TributeAlbum = function(title, artist, tributeArtist)
{
Wrox.ASPAJAX.Samples.TributeAlbum.initializeBase(this, [title, artist]);
this._tributeArtist = tributeArtist;
}
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class-Inheritance
ASP.NET
Library
– Type
: Class
- Inheritance
Wrox.ASPAJAX.Samples.TributeAlbum.prototype = {
get_tributeArtist: function() {
return this._tributeArtist;
},
set_tributeArtist: function(tributeArtist) {
this._tributeArtist = tributeArtist;
}
}
Wrox.ASPAJAX.Samples.TributeAlbum.registerClass('Wrox.ASPAJAX.Samples.TributeAlbum',
Wrox.ASPAJAX.Samples.Album);
var anotherAlbum = new Wrox.ASPAJAX.Samples.TributeAlbum("Groove", "Various Artists",
"Phish");
var title=anotherAlbum.get_title ();
var tributeartist=anotherAlbum.get_tributeArtist();
alert("Title:"+title+",TributeArtist:"+tributeartist);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div> <asp:ScriptManager runat="server" ID="sm" /> </div>
</form>
</body>
</html>
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class-Inheritance
ASP.NET
Library
– Type
: Class
- Inheritance
The constructor must explicitly call initializeBase and pass itself, using the this
keyword, along with an array of the arguments to pass to the constructor of the
base type.
The call to initializeBase takes care of producing the final type with inheritance
semantics in place. The base class constructor is called with the arguments
provided.
The type system of the AJAX Library also provides some reflection functions to
explore the relationship between objects.
if (Wrox.ASPAJAX.Samples.TributeAlbum.isInstanceOfType(anotherAlbum) == true)
{
alert("anotherAlbum is a TributeAlbum");}
if (Wrox.ASPAJAX.Samples.TributeAlbum.inheritsFrom(Wrox.ASPAJAX.Samples.Album)
==true )
{
alert("TributeAlbum inherits from Album");}
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class-Interface
ASP.NET
Library
– Type
: Class
- Interface
Interfaces are a convenient way to define standard behaviors that other types can
implement .
An interface is a contract that states that the implementer of the interface must
provide all of the functionality specified in the interface.
The interface itself is only a specification and has no functionality of its own
Interface definitions follow the same pattern as creating classes
The function name is the name of the interface. The prototype of the function is
modified to add the interface members.
The convention in defining interface members is to throw Error.notImplemented for
each member, so any class that implements the interface then needs to override
the interface members to provide real implementations or the exception will be
thrown.
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class-Interface
ASP.NET
Library
– Type
: Class
- Interface
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET AJAX Interface</title>
<script type="text/javascript">
function pageLoad(sender, args)
{
Type.registerNamespace('Wrox.ASPAJAX.Samples');
Wrox.ASPAJAX.Samples.IProvideTrackInfo = function() {
throw Error.notImplemented();
}
Wrox.ASPAJAX.Samples.IProvideTrackInfo.prototype = {
get_trackCount: function() {
throw Error.notImplemented();
}
}
Wrox.ASPAJAX.Samples.IProvideTrackInfo.registerInterface
('Wrox.ASPAJAX.Samples.IProvideTrackInfo');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div> </div>
</form>
</body>
</html>
ASP.NETAJAX
AJAXClient
Client
LibraryTypeSystem
System:
Class-Enumeration
ASP.NET
Library
– Type
: Class
– Enumeration
The ASP.NET AJAX type system provides
for defining enumerations and a
specialized version of them used as
combinable flags.
Enums let you establish a set of possible
values
function pageLoad(sender, args) {
Type.registerNamespace('Wrox.ASPAJAX.Samples');
Wrox.ASPAJAX.Samples.MusicGenre = function() {
throw Error.invalidOperation();
}
Wrox.ASPAJAX.Samples.MusicGenre.prototype = {
Blues:
1,
Classical:
2,
Electronic:
3,
Folk:
4,
Industrial:
5,
Jazz:
6,
NewAge:
7,
HipHop:
8,
Rock:
9,
WorldFusion:
10
}
Wrox.ASPAJAX.Samples.MusicGenre.registerEnum
('Wrox.ASPAJAX.Samples.MusicGenre');
var genre =
Wrox.ASPAJAX.Samples.MusicGenre.Industrial;
}
alert(Wrox.ASPAJAX.Samples.MusicGenre.toString(g
enre));
alert(genre ==
Wrox.ASPAJAX.Samples.MusicGenre.Industrial);
ASP.NETAJAX
AJAXClient
Client
LibraryAJAXBase
BaseClass
ClassLibrary
Library
ASP.NET
Library
– AJAX
Microsoft ASP.NET AJAX provides features that helps in creating client script and
integrate it into ASP.NET applications. This includes extensions to existing
ECMAScript (JavaScript) objects to give them the richness of .NET Framework
classes
The AJAX Library takes a familiar set of features from the Base Class Library of the
.NET Framework and brings it to JavaScript in the browser
Extensions to JavaScript base types provide additional functionality for these types.
•
Array Type Extensions
•
Boolean Type Extensions
•
Date Type Extensions
•
Error Type Extensions
•
Number Type Extensions
•
Object Type Extensions
•
String Type Extensions
ASP.NETAJAX
AJAXNetworking
Networking
ASP.NET
The core of AJAX development is the ability to make asynchronous web service calls from
JavaScript code.
Major web browsers have included an XMLHttpRequest object for making HTTP requests.
The XMLHttpRequest object is used to perform out-of-band communications with the server for
invoking web services, executing callbacks, and performing partial page updates.
ASP.NET AJAX provides classes for managing web requests, processing responses, and
detecting errors. It also provides support for serializing objects formatted as JSON
(JavaScript Object Notation), which makes them readily usable in JavaScript in the
browser.
•
JSON is a standard serial format that is more lightweight than XML.
ASP.NETAJAX
AJAXNetworking
NetworkingXMLHttpRequest
Object
ASP.NET
– XMLHttpRequest
Object
Remote Scripting:
•
To minimize the impact of page redraws, primitive forms of scripted remote procedure
calls (RPC) appeared around 1997. Microsoft, in particular, pioneered this field with a
technology called Remote Scripting (RS).
•
RS employed a Java applet to pull in data from a remote Active Server Pages (ASP)based URL. The URL exposed a contracted programming interface through a target
ASP page and serialized data back and forth through plain strings. On the client, a
little JavaScript framework received data and invoked a user-defined callback to
update the user interface via Dynamic HTML or similar techniques. RS worked on both
Internet Explorer 4.0 and Netscape Navigator 4.0 and older versions.
Microsoft replaced the Java applet with a Component Object Model (COM) object named
XMLHttpRequest and released most of the constraints on the programming interface
exposed by the remote URL.
ASP.NETAJAX
AJAXNetworking
NetworkingXMLHttpRequest
Object
ASP.NET
– XMLHttpRequest
Object
Browsers generally place a new request when an HTML form is submitted either via clientside
script or through a user action such as a button click. When the response is ready, the
browser replaces the old page with the new one
The out-of-band call is triggered via script by an HTML page event and is served by a proxy
component based on the XMLHttpRequest object
The proxy component sends a regular HTTP request and waits, either synchronously or
asynchronously, for it to be fully served. When the response data is ready, the proxy
invokes a user-defined JavaScript callback to refresh any portion of the page that needs
updating.
ASP.NETAJAX
AJAXNetworking
NetworkingXMLHttpRequest
Object
ASP.NET
– XMLHttpRequest
Object
In Mozilla browsers XMLHttpRequest looks like a native JavaScript object and can be
instantiated through the classic new operator:
var proxy = new XMLHttpRequest();
When the browser is Internet Explorer, the XMLHttpRequest object is instantiated using the
ActiveXObject wrapper
var proxy = new ActiveXObject("Microsoft.XmlHttp");
XMLHttpRequest in Internet Explorer 7
var proxy = new XMLHttpRequest();
ASP.NET AJAX Extensions completely encapsulates this object and shields page authors and
application designers from it
ASP.NETAJAX
AJAXNetworking
NetworkingXMLHttpRequest
Object
ASP.NET
– XMLHttpRequest
Object
The XMLHttpRequest object is designed to perform one key operation: sending an HTTP
request. The request can be sent either synchronously or asynchronously.
interface XMLHttpRequest {
function onreadystatechange;
readonly unsigned short readyState;
void open(string method, string url);
void open(string method, string url, bool async);
void open(string method, string url, bool async, string user);
void open(string method, string url, bool async,
string user, string pswd);
void setRequestHeader(string header, string value);
void send(string data);
void send(Document data);
void abort();
string getAllResponseHeaders();
string getResponseHeader(string header);
string responseText;
Document responseXML;
unsigned short status;
string statusText;
};
ASP.NETAJAX
AJAXNetworking
NetworkingXMLHttpRequest
Object-Example
ASP.NET
– XMLHttpRequest
Object
- Example
(Time.aspx) is a web page that returns the server time to its caller. It takes no
parameters and returns a string .
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Time Page</title>
<script runat="server">
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
Response.Write("Server Time:"+DateTime.Now.ToUniversalTime());
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
ASP.NETAJAX
AJAXNetworking
NetworkingXMLHttpRequest
Object-Example
ASP.NET
– XMLHttpRequest
Object
- Example
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Networking using XMLHttpRequestObject</title>
<script type="text/javascript">
var xmlhttp;
function pageLoad() {
if(window.ActiveXObject) {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "Time.aspx", true);
xmlhttp.onreadystatechange =
readyStateChangedHandler;
xmlhttp.send();
}
function readyStateChangedHandler() {
if(xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server“
ID="ScriptManager1">
</asp:ScriptManager>
</form>
</body>
</html>
(CallTime.aspx) shows basic usage of the
XMLHttpRequest object to call the time
web page
ASP.NETAJAX
AJAXNetworking
NetworkingData
Communication
ASP.NET
– Data
Communications
An important part of any type of distributed application is how data is pushed around between
tiers or layers of the application
With AJAX, the following concepts are important
•
XML—XML is Extensible Markup Language. It is primarily used for data interchange.
•
XSLT—XSLT is Extensible Stylesheet Language Transformations. XSLT is designed to
take XML data from one format and put it into another format.
•
JSON—JSON is the JavaScript Object Notation. JSON is a lightweight data interchange
format.
When tied together with web services, XML and JSON allow for data interchange between
different operating systems and also across the Internet.
ASP.NETAJAX
AJAXNetworking
NetworkingData
Communication-JSON
ASP.NET
– Data
Communications
- JSON
JSON is the JavaScript Object Notation, and it is a lightweight data interchange format.
JSON's chief advantage over XML is that the data may be parsed fairly easily using JavaScript's
built-in eval() method.
JSON is conceptually similar to arrays and collections in procedural programming languages.
JSON is built on the following data structures:
•
Name/value pairs—This may be called an object, record, structure (struct), HashTable,
keyed list, or associated array.
•
List of values—This list of values is referred to an array in most programming
languages.
WebServices
Services
JavaScript
Web
and&JavaScript
ASP.NET 2.0 AJAX Extensions enables the call to 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.
Calling a Web service method from script is asynchronous.
To get a return value or to determine when the request has returned, 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.
Provide a failed callback function to handle errors.
WebServices
Services
JavaScript-Example
Web
and&JavaScript
- Example
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Xml;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ServerTime :
System.Web.Services.WebService
{
[WebMethod]
public string GetServerTime()
{
return String.Format("The server time is
{0}.",
DateTime.Now);
}
}
WebServices
Services
JavaScript-Example
Web
and&JavaScript
- Example
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<style type="text/css">
body { font: 11pt Trebuchet MS;
font-color: #000000;
padding-top: 72px;
text-align: center }
.text { font: 8pt Trebuchet MS }
</style>
<title>Simple Web Service</title>
<script type="text/javascript">
// This function calls the Web Service method.
function GetServerTime()
{
ServerTime.GetServerTime(OnSucceeded);
}
// This is the callback function that
// processes the Web Service return value.
function OnSucceeded(result)
{
var RsltElem =
document.getElementById("Results");
RsltElem.innerHTML = result;
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:ScriptManager runat="server"
ID="scriptManager">
<Services>
<asp:ServiceReference
path="ServerTime.asmx" />
</Services>
</asp:ScriptManager>
<div>
<h2>Server Time</h2>
<p>Calling a service that returns the
current server time.</p>
<input id="EchoButton" type="button"
value="GetTime"
onclick="GetServerTime()" />
</div>
</form>
<hr/>
<div>
<span id="Results"></span>
</div>
</body>
</html>
RichAJAX
AJAXToolkit
ToolKit
Controls
Rich
Controls
The Toolkit is a shared source project with code contributions from developers from Microsoft
and elsewhere.
The Toolkit contains some new controls that have AJAX functionality and a lot of control extenders. The control extenders attach to another control to enhance or “extend” the control’s
functionality .
An extender is basically a server control that emits proper script code—the client behavior—to
enhance how a given ASP.NET control behaves on the client
Server
Reference
Server
Reference
System.Web.ConfigurationThe System.Web.Configuration namespace contains classes that
enable in programmatically accessing configuration elements of Microsoft ASP.NET 2.0 AJAX
Extensions.
System.Web.HandlersThe System.Web.Handlers namespace contains HTTP handler classes
that process HTTP requests to a Web server.
System.Web.Script.SerializationThe System.Web.Script.Serialization namespace contains
classes that provide JavaScript Object Notation (JSON) serialization and deserialization for
managed types. It also provides extensibility features to customize serialization behavior.
Server
Reference
Server
Reference
System.Web.Script.ServicesThe System.Web.Script.Services namespace provides attributes
to customize Web service support for using Microsoft ASP.NET 2.0 AJAX Extensions.
System.Web.UIThe System.Web.UI namespace provides classes and interfaces that enable
client-server communication and rich UI through the use of the Microsoft ASP.NET 2.0 AJAX
Extensions.
System.Web.UI.DesignThe System.Web.UI.Design namespace contains classes that can be
used to extend design-time support for Microsoft ASP.NET 2.0 AJAX Extensions.
ClientReference
Reference
Client
Global Namespace
•
Contains members and types that extend base ECMAScript (JavaScript) objects and
that provide members that are more familiar to .NET developers. Includes extensions
for the JavaScript Array, Boolean, Error, Number, Object, and String types.
Sys
•
Represents the root namespace for the Microsoft AJAX Library, which contains all
fundamental classes and base classes.
Sys.Net
•
Contains types related to communication between ASP.NET AJAX client applications
and Web services on the server.
ClientReference
Reference
Client
Sys.Serialization
•
Contains types related to data serialization for ASP.NET AJAX client applications
Sys.Services
•
Contains types that provide client script access in ASP.NET AJAX to ASP.NET
authentication service, profile service, and other application services.
Sys.UI
•
Contains types related to user interface (UI), such as controls, events, and UI
properties in the Microsoft AJAX Library.
Sys.WebForms
•
Contains types related to partial-page rendering in the Microsoft AJAX Library.
Course
Reference
Course
Reference
Professional ASP.NET 2.0 AJAX
by Matt Gibbs and Dan Wahlin
Wrox Press © 2007
Introducing Microsoft ASP.NET AJAX
by Dino Esposito
Microsoft Press © 2007
ASP.NET AJAX UpdatePanel Control
by Matt Gibbs and Bertrand Le Roy
O'Reilly 2006
Beginning Ajax with ASP.NET
by Wallace B. McClure, Scott Cate, Paul Glavich and Craig Shoemaker
Wrox Press © 2006
www.asp.net/ajax
Questions / Feedback
Thank You!
Descargar

ASP.NET2.0 AJAX