Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Introduce
What is ASP.NET AJAX
Architecture of ASP.NET AJAX
Goal of ASP.NET AJAX
Scenarios
ASP.NET AJAX Extensions
Microsoft AJAX Library
ASP.NET AJAX ToolKit
What is ASP.NET AJAX
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
A framework for quickly creating efficient and
interactive web applications
Architecture of ASP.NET AJAX
Two major components
Microsoft AJAX Library (client)
ASP.NET 2.0 AJAX Extensions (server)
Client
Server
XHTML/CSS
Server Scripts
Microsoft AJAX Library
ASPX
ASP.NET 2.0 AJAX Extensions
Base Class Library
Script Core Library
ASMX
AJAX
Server Controls
Application
Services Bridge
Asynchronous
Communications
Asynchronous Communications
Browser Compatibility
Browsers (IE, Firefox, Safari, others)
ASP.NET 2.0
Page
Framework and
Server Controls
Application
Services
Goal of ASP.NET AJAX
Cross-platform, browser-indepedent
Increased productivity, less time to market
Highly extensible
Enhance existing pages using powerful
AJAX controls
Can be used with PHP, ColdFusion, etc.
Scenarios to develop web application
with ASP.NET AJAX
Server-centric Ajax Web Development
Enrich applications without lots of Javascript code
required
Enable you to keep core UI/Application logic on
server (VB/C#)
Client-centric Ajax Web Development
Leverage full power of script/DHTML
Provide richer and more interactive user experience
ASP.NET AJAX provides a great Ajax framework for
both server and client centric Ajax development
scenarios
Server-Centric Programming Model
ASP.NET Application
Browser
Page Request
Presentation
(HTML/CSS)
Initial Rendering
(UI + Behavior)
Input Data
Updated UI + Behavior
Microsoft Ajax Library
Component/UI
Framework,
Controls
Pages
UI Behavior
(Managed
Code)
ASP.NET
Client
Application
Services
Page
Framework,
Server Controls
Application
Services
Client-Centric Programming Model
ASP.NET Application
Browser
Page Request
Presentation
(HTML/CSS)
Initial Rendering
(UI + Behavior)
Service
Proxies
UI Behavior
(Script)
Component/UI
Framework,
Controls
Data
Web
Services
Data
Microsoft Ajax Library
Pages
ASP.NET
Client
Application
Services
Page
Framework,
Server Controls
Application
Services
ASP.NET AJAX Extensions
Browser-agnostic but not platform-agnostic
Support programming easily
ScriptManager, UpdatePanel, and others
Familiar drag-and-drop design paradigm
Built-in Web services provide bridge to key
ASP.NET 2.0 application services
ASMX extensions enable Web services to
be called through JavaScript proxies
Architecture
ASPX
ASMX
ASP.NET AJAX Extensions
Application Services
Bridge
Server
Controls
Asynchronous
Communications
ASP.NET 2.0
Page Framework
& Server Controls
Application
Services
Server Asynchronous Communications Layer
Server Asynchronous Communications Layer
Web Service
Page Methods
Profile Services
Authentication
Service
JSON Serialization
Xml Serialization
Http Handler
Server Controls
Script
Management
Partial-Page
Rendering
ScriptManager
UpdatePanel
DragOverlayExtender
ScriptManagerProxy
UpdateProgress
ProfileService
Timer
Futures CTP
ScriptManager
Starting point for ASP.NET AJAX pages
What does ScriptManager do?
Downloads JavaScript files to client
Enables partial-page rendering using
UpdatePanel
Provides access to Web services via clientside proxies
Manages callback timeouts, provides error
handling options and infrastructure, and more
Every page requires one ScriptManager!
ScriptManager Schema
<asp:ScriptManager ID="ScriptManager1" Runat="server"
EnablePartialRendering="true|false"
EnablePageMethods="true|false"
AsyncPostBackTimeout="seconds"
AsyncPostBackErrorMessage="message"
AllowCustomErrorsRedirect="true|false"
OnAsyncPostBackError="handler"
EnableScriptGlobalization="true|false"
EnableScriptLocalization="true|false"
ScriptMode="Auto|Inherit|Debug|Release"
ScriptPath="path">
<Scripts>
<!-- Declare script references here -->
</Scripts>
<Services>
<!-- Declare Web service references here -->
</Services>
</asp:ScriptManager>
Script References
"Name" references load script resources
<asp:ScriptManager ID="ScriptManager1" Runat="server">
<Scripts>
<asp:ScriptReference Name="PreviewScript.js"
Assembly="Microsoft.Web.Preview" />
<asp:ScriptReference Name="PreviewDragDrop.js"
Assembly="Microsoft.Web.Preview" />
<asp:ScriptReference Path="~/Scripts/UIMap.js" />
</Scripts>
</asp:ScriptManager>
"Path" references load script files
Service References
<asp:ScriptManager ID="ScriptManager1" Runat="server">
<Services>
<asp:ServiceReference Path="WebServiceDemo.asmx " />
</Services>
</asp:ScriptManager>
ScriptManagerProxy
"Proxy" for ScriptManager controls
declared in master pages
Lets content pages declare script and
service references
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" Runat="server">
<Scripts>
<!-- Declare additional script references here -->
</Scripts>
<Services>
<!-- Declare additional service references here -->
</Services>
</asp:ScriptManagerProxy>
UpdatePanel
Partial-page rendering in a box
Clean round trips to server and updates
Requires no knowledge of JavaScript or AJAX
Leverages PageRequestManager class
EnablePartialRendering="true"
Supports explicitly defined triggers
Postbacks from controls in UpdatePanel are
converted into async callbacks
UpdatePanel Schema
<asp:ScriptManager ID="ScriptManager1" Runat="server"
EnablePartialRendering="true" />
.
.
.
<asp:UpdatePanel ID="UpdatePanel1" Runat="server"
UpdateMode="Always|Conditional"
ChildrenAsTriggers="true|false">
<Triggers>
<!-- Define triggers (if any) here -->
</Triggers>
<ContentTemplate>
<!-- Define content here -->
</ContentTemplate>
</asp:UpdatePanel>
Triggers
AsyncPostBackTrigger
Converts postbacks into async callbacks
Typically used to trigger updates when
controls outside an UpdatePanel post back
If ChildrenAsTriggers="false", can be used to
specify which controls inside UpdatePanel
should call back rather than post back
PostBackTrigger
Lets controls inside UpdatePanel post back
Typically used to allow certain controls to post
back when ChildrenAsTriggers="true"
Triggers Example
<asp:UpdatePanel ID="UpdatePanel1" Runat="server"
UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
<asp:AsyncPostBackTrigger ControlID="TreeView1"
EventName="TreeNodeExpanded" />
<asp:AsyncPostBackTrigger ControlID="TreeView1"
EventName="TreeNodeCollapsed" />
<asp:PostBackTrigger ControlID="Button2" />
</Triggers>
<ContentTemplate>
...
</ContentTemplate>
</asp:UpdatePanel>
Periodic Updates
Combine UpdatePanel with Timer control
to perform periodic updates
Use Timer control Tick events as triggers
<asp:Timer ID="Timer1" Runat="server" Interval="5000"
OnTick="OnTimerTick" />
...
<asp:UpdatePanel UpdateMode="Conditional" ...>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>
...
</asp:UpdatePanel>
UpdateProgress
Companion to UpdatePanel controls
Displays custom template-driven UI for:
Indicating that an async update is in progress
Canceling an async update that is in progress
Automatically displayed when update
begins or "DisplayAfter" interval elapses
UpdateProgress Schema
<asp:UpdateProgress ID="UpdateProgress1" Runat="server"
DisplayAfter="milliseconds"
DynamicLayout="true|false"
AssociatedUpdatePanelID="UpdatePanelID">
<ProgressTemplate>
<!-- Declare UpdateProgress UI here -->
</ProgressTemplate>
</asp:UpdateProgress>
UpdateProgress Example
Display after ½ second
<asp:UpdateProgress DisplayAfter="500" ...>
<ProgressTemplate>
<asp:Image ID="ProgressImage" Runat="server"
ImageUrl="~/Images/SpinningClock.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
Animated GIF
Canceling an Update
<asp:UpdateProgress DisplayAfter="500" ...>
<ProgressTemplate>
<b>Working...</b>
<asp:Button ID="CancelButton" Runat="server" Text="Cancel"
OnClientClick="cancelUpdate(); return false" />
</ProgressTemplate>
</asp:UpdateProgress>
<script type="text/javascript">
function cancelUpdate()
{
var obj = Sys.WebForms.PageRequestManager.getInstance();
if (obj.get_isInAsyncPostBack())
obj.abortPostBack();
}
</script>
ASP.NET AJAX Web Services
ASP.NET AJAX supports ASMX Web
methods as endpoints for asynchronous
AJAX callbacks
Efficient on the wire (no SOAP or XML)
Efficient on the server (no page lifecycle)
ScriptService attribute on server indicates
Web service is callable from script
JavaScript proxy on client enables
JavaScript clients to call Web methods
Script-Callable Web Service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebServiceDemo : System.Web.Services.WebService {
[WebMethod]
public string HelloWorld(string message) {
return (message + " : " + DateTime.Now.ToLongTimeString());
}
}
Declaring a Service Reference
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServiceDemo.asmx" />
</Services>
</asp:ScriptManager>
<script src="WebServiceDemo.asmx/js" type="text/javascript">
</script>
Consuming a Web Service
function GetResult()
{
var content = $get('location').value;
WebServiceDemo.HelloWorld(content, OnSuccess, OnFailure);
}
function OnSuccess(result, context, methodName)
{
$get('result').innerHTML = result;
}
Handling Errors
function GetResult()
{
var content = $get('location').value;
WebServiceDemo.HelloWorld(content, OnSuccess, OnFailure);
}
function OnSuccess(result, context, methodName)
{
$get('result').innerHTML = result;
}
function OnFailure(error, context, methodName)
{
var errorMessage = error.get_message();
$get('result').innerHTML = errorMessage;
}
Page Methods
Script-callable Web methods in pages
Simpler than Web services
Do not require service references
Do not require dedicated ASMX files
Must be public static methods
Must be enabled via ScriptManager.EnablePageMethods (disabled by default)
Called through PageMethods proxy on
client
Enabling Page Methods
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true"
Runat="server" />
Defining a Page Method
public partial class PageMethodDemo: System.Web.UI.Page
{
...
[WebMethod]
public static string HelloWorld(string message)
{
return (message + " : " + DateTime.Now.ToLongTimeString());
}
...
}
Calling a Page Method
function GetResult()
{
var content = $get('location').value;
PageMethods.HelloWorld(content, OnSuccess, OnFailure);
}
function OnSuccess(result, context, methodName)
{
$get('result').innerHTML = result;
}
function OnFailure(error, context, methodName)
{
var errorMessage = error.get_message();
$get('result').innerHTML = errorMessage;
}
Built-In Web Services
AuthenticationService
Front end to membership service
Sys.Services.AuthenticationService proxy
Global instance of
Sys.Services._AuthenticationService
ProfileService
Front-end to profile service
Sys.Services.Profile proxy
Global instance of Sys.Services._ProfileService
Accessed through ScriptHandlerFactory
Microsoft AJAX Library
Client half of ASP.NET AJAX
Browser-agnostic and platform-agnostic
Internet Explorer, Firefox, Opera, Safari, etc.
Leverage it from PHP and other platforms
Enhances JavaScript with type system
Namespaces, classes, interfaces, etc.
Packaged in *.js files downloaded to clients
Architecture
XHTML/CSS
Server Scripts
Microsoft AJAX Library
Base Class Library
Script Core Library
Asynchronous Communications
Browser Compatibility
Browsers (IE, Firefox, Safari, others)
Client Asynchronous Communications Layer
Client Asynchronous Communications Layer
Web Service
Proxies
Page Methods
Proxies
Profile
Proxies
Authenticate
Proxies
WebRequest
WebRequestManager
XmlHttpExecutor
JSON
Serializer
XmlHttp
Client-Server Communication
Service
Proxies
UI Behavior
(Script)
Client
Asynchronous Communication
Presentation
(HTML/CSS)
Page Request
Initial Rendering
(UI + Behavior)
Data
Data
Server
Asynchronous Communication
ASP.NET Application
Browser
Pages
Web
Services
Global Functions
Helper functions for use anywhere
Used in JavaScript emitted by controls
Function
Description
$create
Creates and initializes a component
$find
Retrieves the component with the specified ID
$get
Retrieves the DOM element with the specified ID
$addHandler(s)
Registers handlers for DOM event(s)
$clearHandlers
Unregisters handlers for DOM events
$removeHandler
Unregisters a handler for a DOM event
Base Type Extensions
Microsoft AJAX Library extends the
following JavaScript types
Array - add, addRange, contains, insert, etc.
Boolean - parse
Date - format, parselocale, parseInvariant, etc.
Error - argumentOutOfRange, etc.
Number - format, parseLocale, parseInvariant
Object - getType, getTypeName
String - format, endsWith, startWith, trim, etc.
String.Format
var s = String.format ('{0}, {1}, and {2}', 1, 2, 3);
window.alert (s);
Adding OOP to JavaScript
Object-based but not object-oriented
Microsoft AJAX Library adds OOP to
JavaScript
Namespaces
Classes and inheritance
Interfaces and enumerated types
prototype property forms basis for
"classes"
Type class provides typing and type
reflection
JavaScript "Classes"
Person = function(name) {
this._name = name;
}
Person.prototype = {
get_name: function() {
return this._name;
}
// Declare other class methods here
}
Using the Person Class
var p = new Person(‘A');
// Displays “A"
window.alert(p.get_name());
Type Class
Adds typing and reflection to JavaScript
Adds key instance methods to all types
registerClass, registerInterface
initializeBase, getBaseType
getBaseMethod, callBaseMethod, and others
Implements key "static" methods
registerNamespace
isNamespace, isClass, isInterface, and others
Implemented in MicrosoftAjax.js
Registering Namespaces and
Classes
Type.registerNamespace(‘MyNameSpace');
MyNameSpace.Person = function(name) {
this._name = name;
}
MyNameSpace.Person.prototype = {
get_name: function() {
return this._name;
}
}
MyNameSpace.Person.registerClass('MyNameSpace.Person');
Using MyNameSpace.Person
var p = new MyNameSpace.Person(‘A');
// Displays “A"
window.alert(p.get_name());
// Displays " MyNameSpace.Person"
window.alert(Object.getTypeName(p));
JavaScript Files
Internet
Explorer
Firefox
MicrosoftAjax.js
PreviewWebForms.js
Partial-page rendering
MicrosoftAjaxTimer.js
Sys.UI._Timer class
PreviewScript.js
Safari
PreviewGlitz.js
Other
Script Core Library
(run-time + framework)
PreviewDragDrop.js
Base Class Library
(controls, XML script, etc.)
UI enhancements
(animation and opacity)
Drag-and-drop
MicrosoftAjax.js
Sys
Sys.Net
Sys.Services
Sys.Serialization
Sys.UI
StringBuilder
WebRequestExecutor
_ProfileService
JavaScriptSerializer
DOMElement
_Debug
XMLHttpEXecutor
ProfileGroup
DOMEvent
EventArgs
_WebRequestManager
_AuthenticationService
Behavior
Component
WebRequest
Control
_Application
WebServiceProxy
Point
CultureInfo
WebServiceError
Bounds
Other
Other
_Timer
StringBuilder
var sb = new Sys.StringBuilder();
for (var i = 1; i <= 100; i++)
{
sb.append(i); // Count from 1 to 100
sb.append('<br/>');
}
var text = sb.toString(); // Get the results
PreviewWebForms.js
Partial-page rendering support
PageRequestManager class
Client-side counterpart to UpdatePanel
Manages async callbacks used for partialpage rendering and performs content updates
using results
Client-side OM enables advanced
UpdatePanel customizations not possible from
server side
_UpdateProgress class
PageRequestManager Methods
Provide programmatic control over clientside PageRequestManager
Method
Description
get_isInAsyncPostBack
Indicates whether async callback is in progress
getInstance
Returns reference to current PageRequestManager instance
abortPostBack
Cancel the async callback that is currently in progress
add_*
Registers handlers for PageRequestManager events
remove_*
Deregisters handlers for PageRequestManager events
PageRequestManager Events
PageRequestManager fires events
Hook events on client for advanced
customizations
Event
Description
initializeRequest
Fired before async callback commences
beginRequest
Fired when async callback commences
pageLoading
Fired following an async callback (before content is updated)
pageLoaded
Fired following a postback or callback (after content is updated)
endRequest
Fired when async callback completes
PreviewScript.js
Sys.Preview.Data Sys.Preview.UI.Data
Other
Namespaces
Sys.Preview
Sys.Preview.UI
BindingBase
Color
DataColumn
DataControl
ServiceMethodRequest
Binding
Validator
DataRow
DataNavigator
Profile
Action
Label
DataTable
ItemView
Other
InvokeMethodAction
Button
DataView
ListView
SetPropertyAction
CheckBox
DataFilter
XSLTView
Timer
TextBox
DataSource
Other
Counter
Selector
Other
Other
Other
Sys.Preview.UI
Classes that abstract HTML control
elements
Button, Label, TextBox, Selector, etc.
Base functionality defined in Sys.UI.Control
get_visible, set_visible
get_parent, set_parent
And so on
Control classes simplify JavaScript and
facilitate browser independence
Using Control Classes
<input type="text" id="Input" />
<input type="button" id="MyButton" value="Click Me" />
<span id="Output" />
...
<script type="text/javascript">
var g_textBox;
var g_label;
function pageLoad()
{
g_textBox = new Sys.Preview.UI.TextBox($get('Input'));
var button = new Sys.Preview.UI.Button($get('MyButton'));
g_label = new Sys.Preview.UI.Label($get('Output'));
button.initialize();
button.add_click(onClick);
}
function onClick()
{
g_label.set_text(g_textBox.get_text());
}
</script>
Sys.Preview.[UI.].Data
Contains classes that
support rich client-side
data binding
ItemView and ListView
do client-side
rendering
DataSource links data
consumers to data
service and supports
2-way data binding
Sys.Preview.Data Sys.Preview.UI.Data
DataColumn
DataControl
DataRow
DataNavigator
DataTable
ItemView
DataView
ListView
DataFilter
XSLTView
DataSource
Other
Other
PreviewDragDrop.js
Adds drag-drop support to BCL
_DragDropManager provides core support
Global instance named DragDropManager
IDropSource and IDropTarget interfaces
define signatures for drop-source and
drop-target classes
FloatingBehavior provides generic
mechanism for floating images, DIVs, and
other entities
Floating an Image
<img id="FloatMe" src="...">
...
<script type="text/javascript">
function pageLoad()
{
var float = new Sys.Preview.UI.FloatingBehavior
($get('FloatMe'));
float.set_handle($get('FloatMe'));
float.initialize();
}
</script>
PreviewGlitz.js
Adds UI enhancements to BCL
OpacityBehavior class wraps opacity
LayoutBehavior class wraps layout
Animation and derivatives support
animations
PropertyAnimation
NumberAnimation
InterpolatedAnimation
LengthAnimation
DiscreteAnimation
CompositeAnimation
FadeAnimation
Fading In an Image
<img id="SplashImage" src="...">
...
<script type="text/javascript">
function pageLoad()
{
var image = new Sys.Preview.UI.Image ($get('SplashImage'));
var fade = new Sys.Preview.UI.Effects.FadeAnimation();
fade.set_target(image);
fade.set_effect (Sys.Preview.UI.Effects.FadeEffect.FadeIn);
fade.set_duration(3);
fade.set_fps(20);
fade.play();
}
</script>
ASP.NET AJAX Control Toolkit
More server controls, plus SDK for custom
controls
Community-owned and driven, shared
source