You are on page 1of 34

Training Programme

( Zed-Axis Technologies Pvt. Ltd. )

Introducing the
Advanced Ajax And Ajax.Net
Control Toolkit for Asp.NET

By: Praveen Kumar


Introduction

Client Server Architecture


AJAX(Asynchronous JavaScript and XML)
AJAX = JAVASCRIPT+HTML+DHTML+DOM+CSS+XML
 What is AJAX, and why do we care?
 The XmlHttpRequest revolution

Look up at ASP.NET AJAX and Control


Toolkit
Agenda

Understanding AJAX & XmlHttpRequest


Understanding ASP.NET AJAX
ASP.NET AJAX Architecture
ASP.NET AJAX Client Life-Cycle events
ASP.NET 2.0 AJAX Extensions
ASP.NET AJAX Control Toolkit
Anatomy of Toolkit Component
Client Server Architecture

Asynchronous JavaScript And


XML = is a web development
technique for creating responsive
web applications by exchanging
small amounts of data with the
server behind the scenes
Overview of AJAX
1 Browser submits HTTP
request to server

2 Server responds with content;


browser renders that content

3 Browser submits async XML-


HTTP request to server; UI
remains responsive; page
Browser doesn't flash
Web Server

4 XML-HTTP request completes;


JavaScript refreshes portion of
page affected by response
Time Taken During The Data
Transmission
Client Sitting ideal.

Client making request To


JAVASCRIPT Not Server.
User may continue to work.

Server Responding to
JAVASCRIPT Asynchronous.
JAVASCRIPT updating client.
XmlHttpRequest
 Introduced in 1999 with Internet Explorer 5
– ActiveX object supporting callbacks to Web server
– Created for benefit of Outlook Web Access (OWA)
 Later adopted by Firefox, Safari, and others
– Implemented as native object rather than ActiveX
– Currently being standardized by W3C
 http://www.w3.org/TR/XMLHttpRequest/
 Supported by approx. 99% of browsers used
today
– Approx. 85%-95% have JavaScript enabled
Object Instantiation.
function getobject(){
var reqst = false;
try{
reqst = new XMLHttpRequest();
}
catch(msnew){
try{
reqst = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch(msother){
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (failed) {
request = false;
}
}}}
Methods :
open(); Sets up a new request to a server.
send(); Send a request on server.
readystate; provides current request State.
responseText; The text server send back by server.
responseXML; The Server generated XML response.

ReadyState :
 0: The request is uninitialized (before call open()).
 1: The request is set up, but not sent (before call send()).
 2: The request was sent and is in process.
 3: The request is in process;
 4: The response is complete; you can get the server's response and use it.
 Call Back method is passed to request object by
assigning the onreadystatechange=“function()”
Open Method :
The request open method takes following Args.
 request-type: The type of request to send (Get,Post).
 url: The URL to connect to.
 asynch: Pass here true/false (true if asynch else false).
 username: User name, if authentication required;
 password: Password, if authentication required.
 For Example : -
– open(“GET”,”/myserver/abc.aspx?p1=” + p1,true);
– open(“POST”,”/myserver/abc.aspx”,true);

Send Method :
The parameter for send method is the data in case of data
sent true post method
– send(vname);
– Else Pass null
– send(null);
Demo
Create Request
<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try { request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}}}

if (!request)
alert("Error initializing XMLHttpRequest!");

function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
}
</script>
Open Request
function getCustomerInfo()
{

var phone = document.getElementById("phone").value;

var url = "/local/lookupCustomer.aspx?phone=" + escape(phone);

request.open("GET", url, true);

Set Callback and Send


function getCustomerInfo()
{
var phone = document.getElementById("phone").value;

var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);

request.open("GET", url, true);

request.onreadystatechange = updatePage;

request.send(null);

}
When to process Request
•Do processing of call back method when: -
•Readystate =4;
•Status = 200;
Example: --------------------------------------------------------------------
------------------------------ function updatePage() {

function updatePage() if (request.readyState == 4) {


{
if (request.readyState == 4) { if (request.status == 200) {
if (request.status == 200)
// Do Request Processing var xmlDoc = request.responseXML;
var xmlDoc = request.responseXML; var showElements = xmlDoc.
// if response in XML getElementsByTagName("show");
var txtDoc = request.responseText; // The very first element in XML Document
// if response in Text for (var x=0; x<showElements.length; x++) {
} var title = showElements[x].
else if (request.status == 404) childNodes[0].value;
alert("Request URL does not exist"); var rating = showElements[x].
else childNodes[1].value;
alert("Error: status code is " + }
request.status); }
} }
}
Important HTTP Status Codes
 200 (OK, Request Processed Successfully and Responded.)
 301 (Moved Permanently)
 302 (Found and Redirected to some other URL)
 305 (the request must use a proxy to access the resource requested)
 400 (Bad Request)
 401 (Unauthorized)
 403 (Forbidden)
 404 (Not Found)
 408 (Request Time Out)
 500 (Internal server Errors)

Demo Code – Asynchronous Binding of dropdown control


ASP.NET AJAX
 Framework for building AJAX-enabled Web apps
– Cross-platform, browser-agnostic
– Increased productivity, less time to market
– Highly extensible
 Two major components
– Microsoft AJAX Library (client-side framework)
– ASP.NET 2.0 AJAX Extensions (server-side framework)
 Tightly integrated with ASP.NET 2.0 on server
 Familiar UI elements such as progress indicators,
tool tips, and pop-up windows.
 A framework that simplifies customization of
server controls to include client capabilities.
ASP.NET AJAX Architecture

Client Script
Library
ASP.NET AJAX Server Extensions
Controls, App Services
Components Bridge
ASP.NET AJAX
Component Model Server Controls
Web Services
and UI Framework Bridge
Base Class Library
Client ASP.NET 2.0
Application Script Core
Services Page, Application
Framework, Services
Browser Browser
Server controls
Integration Compatibility

Client Framework & Services Server Framework


Client Server
XHTML/CSS Server Scripts ASPX ASMX

Microsoft AJAX Library ASP.NET AJAX Extensions


Application
Base Class Library
Services Bridge
AJAX
Script Core Library Server Controls
Asynchronous
Communications
Asynchronous Communications
ASP.NET 2.0
Browser Compatibility
Page
Application
Framework and
Browsers (IE, Firefox, Safari, others) Services
Server Controls

The ASP.NET AJAX Library


JavaScript Framework
 Object oriented framework build on JavaScript
 Provides automatic cross-browser compatibility layer
 Built-in classes for WebService calls, Type system, basic
DOM operations
 Allows structured programming and encapsulation
 No more sprinkling JavaScript around your site!
ASP.NET 2.0 AJAX Extensions
 Server half of ASP.NET AJAX
– Browser-agnostic but not platform-agnostic
 Server controls abstract Microsoft AJAX Library
– ScriptManager, UpdatePanel, and others
– Emit content that leverages the client-side framework
– Familiar drag-and-drop design paradigm
 Built-in Web services provide bridge to app services
 ASMX extensions and JSON serializer enable Web services to be called
through JavaScript proxies

Script Partial Service


Management Rendering Extenders Wrappers
AutoComplete-
ScriptManager UpdatePanel ProfileScript
Extender

ScriptManager- DragOverlay-
UpdateProgress
Proxy Extender

Timer
 ScriptManager- One per page to support AJAX features
 ScriptManagerProxy - Use when a .master contains a ScriptManager
already
 UpdatePanel - Allows partial-page updates
 Timer - Raises event at regular interval
 UpdateProgress - Send progress messages back to page

 “ScriptManager” is mandatory to available on page


 Ajax features Which includes:
– Include Asp.Net Ajax Client Script Library.
– Allow partial page rendering/updating.
– Include Java script proxy classes for web services.
– Include Java script classes to access ASP.NET authentication and profile
application services.
 To enable partial page update set EnablePartialRendering=“true” of
“ScriptManager” control.
 Only one instance of the ScriptManager control can be added to the page.
 Syntax:
<asp:scriptmanager id=“ScMngr” runat=“server”
EnablePartialRendering="true"></ asp:scriptmanager>
 The "crown jewel" of ASP.NET AJAX
 Adds partial rendering to pages and controls
– Automatically converts postbacks into async callbacks
– Automatically updates content using callback results
– Requires no knowledge of JavaScript or XmlHttpRequest
 High-level abstraction of XmlHttpRequest and AJAX
– Upside: Extremely easy to use, widely applicable
– Downside: Not as efficient as hand-coded AJAX
 Exemplifies value added by AJAX frameworks
 A control that causes an asynchronous postback is referred
to as a trigger

<asp:ScriptManager ID="..." Runat="server"


EnablePartialRendering="true" />
.
.
<asp:UpdatePanel ID="..." Runat="server">
<Triggers>
<!-- Define triggers (if any) here -->
</Triggers>
<ContentTemplate>
<!-- Define content here -->
</ContentTemplate>
</asp:UpdatePanel>
You write this:
<asp:ScriptManager ID="MyScriptManager" Runat="server" />

ScriptManager emits this: Oblique reference to script file

<script src="/.../WebResource.axd?d=iQ15p6LHcT2T5QE..."
type="text/javascript"></script>

Controlling what gets downloaded.


<asp:ScriptManager ID="..." Runat="server">
<Scripts>
<asp:ScriptReference
Name="Microsoft.Web.Resources.ScriptLibrary.PreviewScript.js"
Assembly="Microsoft.Web.Preview" />
<asp:ScriptReference
Name="Microsoft.Web.Resources.ScriptLibrary.PreviewDragDrop.js"
Assembly="Microsoft.Web.Preview" />
<asp:ScriptReference Path="~/Scripts/UIMap.js" />
</Scripts>
</asp:ScriptManager>
UpdateProgress
 Provides visual feedback in the browser
 when the content of UpdatePanel controls is updated.
 Associate an UpdateProgress control with an UpdatePanel
control by setting the AssociatedUpdatePanelID property of
the UpdateProgress control . <asp:UpdateProgress
ID="UpdateProgress1" runat="server">
<ProgressTemplate>
Please wait…
</ProgressTemplate>
Timer </asp:UpdateProgress>

 The Timer control performs postbacks at defined


 intervals.
 The Timer control performs automated postbacks at defined intervals.
 The JavaScript component initiates the postback from the browser when the interval that is
defined in the Interval property has elapsed.
 The Interval property is defined in milliseconds and has a default value of 60,000
milliseconds, or 60 seconds.
 When a postback was initiated by the Timer control, the Timer control raises the Tick event
on the server.
 Used with updatepanel control. <asp:Timer ID="Timer1" runat="server">
</asp:Timer>
Client Life-Cycle events
 The two main Microsoft AJAX Library
classes that raise events during the
client lifecycle of a page are the
Application and PageRequestManager
classes.

 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.
PageRequestManager Class
 The “Microsoft AJAX Library” manages partial-page
updates in the Browser.
 Exposes properties, methods, and events that enables
customize partial-page updates with client script.
 Use When Required to control: -
– How multiple asynchronous postbacks are processed.
– Display status messages during asynchronous postbacks and
opportunity to cancel the processing.
– Provide custom error-message handling for partial-page
updates.
– Access the underlying request and response objects that are
used for the asynchronous postbacks.

initializeRequest Raised before the request is initialized for an asynchronous


postback
beginRequest Raised just before the asynchronous postback is sent
to the server
pageLoading Raised after the response to the most recent
asynchronous postback has been received but before
any updates to the page have been made.
pageLoaded Raised after page regions are updated after the most recent postback

endRequest Raised when request processing is finished


ASP.NET AJAX Control Toolkit
 More ASP.NET AJAX server controls, plus SDK for control development
 Community-owned, community-driven, shared source
 Most of toolkit controls are extender
 controls
 An extender is a control which extends
 the functionality of another control
Toolkit Controls Overview
AJAX Control Toolkit in the Toolbox
 How to add it to the Toolbox
– Right-click, Add Tab…, AJAX Control Toolkit
– Right-click, Choose Items…,
AjaxControlToolkit.dll
 First time a control is added, DLL is copied
into Bin folder
– Optional: rename TagPrefix to "ajax"
 Most of the new controls are Extenders
– Set the TargetControlID on the extender
control
– Set the Extender properties on the target
control
 Demo: ConfirmButtonExtender
ASP.NET AJAX
Techniques & Practices
1. Using Update Panel
2. Progress Bar Binding with Update Panel
3. Drag a Panel over the screen
4. AutoCompleteExtender
5. Using ASP.NET AJAX Tab Control

<%@ Register Assembly="AjaxControlToolkit"


Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
More about Behaviors and Extenders in ASP.NET AJAX
 Behaviors
– Add or modify functionality to an element on the page
– Written in JavaScript
– Modify the HTML DOM
 Extenders
– ASP.NET components
– Associate an ASP.NET Control with a Behavior
– Leverage Server-Side and Design Time

Creating A Toolkit Component


 Two types of components in the Toolkit
– Behavior + Extender
– “ASP.NET AJAX-aware” Control (ScriptControl)
 Which to choose?
– If required HTML shape is very specific, write a control and then
attach behaviors to it
– If HTML shape is simple or common, write an extender
Anatomy of a Toolkit Component
The Extender
The Behavior
[ClientScript(“…”)]
The Markup
[TargetControlType(typeof(Control))]
The
public Code
MyProject.MyBehavior = function(e) {
class MyExtender :
MyProject.MyBehavior.initializeBase(this, [e]);

<cc1:MyExtender
ExtenderControlBase
this._myStringPropValue = null; runat=“server”
{ this._myStringIntValue
MyExtender TargetControlID=“TextBox1”
=ex1
0; = new MyExtender();
}
[ExtenderProperty]= “Hello”;
ex1.MyStringProp MyStringProp=“Hello”
public string MyStringProp{}
MyProject.MyBehavior.prototype = {
initialize function()MyIntProp=“23”
ex1.MyIntProp { … }, = 23;
ex1.TargetControlID
get_MyStringProp : function(){},
</cc1:MyExtender>
[ExtenderProperty]
set_MyStringProp : function(value){},
= “TextBox1”;
Page.Add(ex1);
public int MyIntProp{}
get_MyIntProp : function(){},
} set_MyIntProp : function(value){}
}
Creating an Extender Project
 Toolkit package has Visual Studio templates
for: • Toolkit-enabled website
• Toolkit component project
• Toolkit Components
• VB & C# for each
Summary / Call to Action
 AJAX = Asynchronous JavaScript and XML
– Better, richer, and more interactive Web apps
 ASP.NET AJAX = Framework for AJAX
development
– Microsoft AJAX Library (client-side framework)
– ASP.NET 2.0 AJAX Extensions (server-side
framework)
 ASP.NET AJAX is…
– Compact and well factored (minimal download size)
– Compatible with a wide range of browsers
– Compatible with PHP, ColdFusion, and other
platforms
 ASP.NET AJAX is the future
Resources
 AJAX Wikipedia entry
– http://en.wikipedia.org/wiki/AJAX
 ASP.NET AJAX Web sites
– http://ajax.asp.net
– http://ajax.asp.net/ajaxtoolkit
– www.ajaxwebwidgets.com
– http://www.asp.net/AJAX
– http://forums.asp.net/default.aspx?GroupID=34
– http://asp.net/AJAX/Documentation/Live/ClientReference/

 Scott Guthrie's blog


– http://weblogs.asp.net/scottgu/
 Lecture Demos/Workshop
– http://cds.fhcrc.org/download.aspx
Thank you!

You might also like