You are on page 1of 62

Ajax 4.

Solution is Ajax

Combines open standard- based technologies

Updates portion of page without blocking


other user action

Asynchronous client-side calls to server


Javascript
Data in various format

Isnt like ASP.NET caching

AJAX or Ajax ?
Goal is to make browser/server interaction
easy and fast.

XMLHttpRequest Object

Most important object in Ajax


Enables communication between browser
and client

Requires Javascript
Degrade gracefully if turned of

Common object across all modern browser

Introduced in IE 5 around 2000


Since has become part of WC3 standard
Slight variations in name and how instantiate

Web Form Processing

Major change in Ajax is in Page


processing
Two option

Traditional full-page processing


Ajax partial-page processing

Initially full page comes to the server

Then can use either full or partial-page


processing

Traditional ASP.NET page


Processing

ASP.NET web forms use full-page


processing

ASP.NET Ajax Processing

After initial load, can update small


sections

ASP.NET Ajax Processing

Ajax requests handled through


XMLHttpRequest object
Bypasses normal page processing

Ajax and Visual Studio

Ajax originally was an add-on to visual studio


2005 and ASP.NET 2.0

Integrated in Visual Studio 2008 and ASP.NET


3.5

Required separate download and installation


Features not fully baked into visual studio

Even tightly bound in Visual Studio 2010 and


ASP.NET 4.0

Javascript debugging is better than ever

Similar to debugging server-side code


Set breakpoints, examine variable values, and more

Debug and Explore Ajax

Debugging Javascript isnt enough

Fiddler

Doesnt show HTTP request and response


Web debugging proxy
Captures HTTP and HTTPs traffic
Inspect, set breakpoints and create requests
Use with any browser

Firebug add-on for FireFox

Explore Javascript & browser interactions with server


XMLHttpRequest Spy
Compelling reason to use FireFox for development

Javascript, the language

A much maligned language

Changed as Javascript takes on a New Role

Despite being the de facto language of the web


Shunned because interpreted, loosely-coupled,
poor tool support
Driving force behind Ajax
All modern browser support it
Less of a problem with users turning of

Historically, inconsistence support in browsers

Not a problem for single version browser


Nightmare if need Cross-Browser support
Good framework eliminates the problem

Object Orientation

Not object oriented like C# and VB

But Javascript is based on objects


Everything is an object in Javascript
.Net objects are instantiated from classes
More like .Net Dictionary class
Create a new property by assigning a value

Var point new Object()


point.X = 10;
point.Y = 20;
point.Z = 30;
Var location = point.X + , + point.Y + , +
point.Z;

Object Orientation
Can associate any arbitrary value with any arbitrary
property of the object
Can have methods, defined as functions
var point = {

X: 10,
Y: 20,
Z: 30,
add: function(p){
this.X = this.X + p.X;
this.Y = this.X + p.Y;
this.Z = this.X + p.Z;

}
}

DHTML

Dynamic HTML
Javascript modifies HTML = DHTML

Most Popular Javascript


Function
The Most popular Javascript function
would be getElementById()
Find element on the page by Id attribute
<div id=mydivtag > </div>
<script language=javascript>
var divtag =
document.getElementById(mydivtag)
</script>

Arrays
A common way to create and append strings
in javascript is to create an Array Object
Array in javascript are Zero based, and not
fixed in length, and can continue to grow
simply by appending to the end of the object
display[ display.Lenght] = Added Text;
To pull content together as one long string,
use the Array.Join(delimiter) method: ( notice
the empty string delimiter in this example).
display.Join();

The innerHTML property


Property used to get or set the inner
content of element
<div id=myDivTag></div>
<script language=javascript>
var divTag =
document.getElementById(myDivTag);
divTag.innerHTML = <h1>Hello
World</h1>
</script>

The style Property

Property to get or set the style of an element


Hundreds of subproperties representing all style
elements

backgroundColor
height
width

<div id=myDivTag></div>
<script language=javascript>
var divTag =
document.getElementById(myDivTag);
divTag.innerHTML = <h1>Hello World</h1>
divTag.style.color = Red;
</script>

Multi-Browser Support

Each browser implements javascript diferently

Can make your code work the same in all browsers


But it is a ton of work
Even diferent version of the same browser change

Ajax framework

Functionality available as single call


Normalizes across most common browsers
Huge benefits

Javascript Object Notation


(JSON)

Plain text data format


Easy to transport over HTTP
Easy to compress, serialize,
deserialize
Simple format: name/value collection

JSON rules (1)


Enclose JSON with single set of parentheses
Enclose name/value pairs in curly brackets
Separate name and value with colon
{Person : Scott}
Separate array of pairs with comma

{Name : Microsoft , url : http://www.Microsoft.com}

Value of name/value pair is often another pair


Value may also be a function

JSON rules (2)

Value of pair may be an array of name values

Enclose within square brackets

({Urls : [
{Name : Microsoft , url : http://www.Microsoft.com}
{Name : Google , url : http://www.Google.com}
{Name : MiSys , url : http://www.Misys.com}

]
})

Array of Url objects, each with Name and Url value

Deserialize the Urls:


var urls = eval(response).Urls;

JSON rules (3)

Iterate the urls array


for ( x=0; x<urls.lenght; x++ ){
var name = urls[x].Name;
var url = urls[x].url;

Dont have to format for humans to read


({Urls : [

{Name : Microsoft , url : http://www.Microsoft.com}


{Name : Google , url : http://www.Google.com}
{Name : MiSys , url : http://www.Misys.com}

]
})

Using JSON

Best serializer for Ajax because works


well with javascript

eval function
Standard JavaScript deserializer

Preferable to XML

JSON is much lighter


XML is verbose
XML is easier to read
JSON is more efficient

Javascript Objects

Object Signature

nav = function(name, url)


{
this.Name = name;
this.Url = url;
}

Create a nav object


var urls = new Array;

urls[urls.lenght] = new
nav(Microsoft,http://www.microsoft.com);
urls[urls.lenght] = new
nav(Google,http://www.google.com);

Cycle through Javascript


Objects
var content = new Array;
content[content.lenght] = <ul>;
for( x=0; x<urls.lenght; x++){
content[content.lenght] = <li>;
content[content.lenght] = <a href=;
content[content.lenght] = urls[x].url;
content[content.lenght] = >;
content[content.lenght] = urls[x].Name;
content[content.lenght] = </a>;
content[content.lenght] = </li>;
}
content[content.lenght] = </ul>;
var result = document.getElementById(result);
result.innerHTML = content.join();

Enclosures

Can create objects with data or functions


Add methods same add text properties

Value of name/value pair is the actual function

nav = function(name, url){


this.Name = name;
this.Url = url;
this.ToLink = function() {
var link = new Array;
link[link.lenght] = <a href=;
link[link.lenght] = this.url;
link[link.lenght] = >;
link[link.lenght] = this.Name;
link[link.lenght] = </a>;
return link.join();
}
}

Enclosures
Using the ToLink method
for (x=0; x<urls.lenght; x++) {
content[content.lenght] = <li>;

content[content.lenght] = urls[x].ToLink();

content[content.lenght] = </li>;
}

Enclosures are defined inside the method


definition

More memory because an enclosure is allocated


along with each object instance

Prototype

Prototypes are added outside of the object definition


nav = function (name, url){
this.Name = name;
this.Url = url;
}

nav.prototype.ToLink = function(){
var link = new Array;
link[link.lenght] = <a href=;
link[link.lenght] = this.url;
link[link.lenght] = >;
link[link.lenght] = this.Name;
link[link.lenght] = </a>;
return link.join();
}

Less memory because a prototype is only allocated


once, and reused for all object instance

Enclosure or Prototypes?

Need to use prototypes?


But client memory is an issue
Object instantiation

Object and all properties and methods take space


in memory
Really just in-memory hash table
If reuse an object

Must create enclosures for each object


One prototype in memory for all objects

Functionally, there is no diference

Server-Side Ajax

Fits nicely in overall ASP.NET page processing


model

Ajax server controls

Relies on ASP.NET server controls


Drag and drop designer support
ScriptManager, updatePanel

Most processing on the server


Feels like development with full page
postbacks
Not all features are baked into Visual Studio

Client-Side Ajax

Closer to original concept of Ajax


Microsofts Ajax Client Ajax

Makes Javascript look like a .NET


language with framework support
Enhanced Visual Studio tools

Library implemented as Javascript file

MicrosoftAjax.js and Microsoft.debug.js

Ajax Server-side Controls

Partial-page postbacks using five


server controls

Same drag and drop/set properties


paradigm as web and windows forms apps

Create Ajax-ified pages with designer


or code editor

Design view doesnt support all Ajax


control features
HTML is relatively straight forward

The ScriptManager Control

Delivers correct scripts to the browser

Only one per page


Usually put on master page, if using
Sole gateway for delivering scripts to page

Script tag

<script src=/myscript.js type=text/javascript />

Not very smart

ScriptManager has no runtime interface

Just manages Ajax and scripts features


Manages messages between browser and server

ScriptManager Property
Collections

Several child collection

AuthenticationService
ProfileService
RoleService
Scripts
Services

Default markup

<asp:ScriptManager id=scriptmanager1 runat=server >


<AuthenticationService />
<ProfileService />
<RoleService />
<Scripts />
<Services />
</asp:ScriptManager>

ScriptReference Control

Use to load JavaScripts files

Guaranteed to load after client-side framework

Load myScript.js

<asp:ScriptManager id=scriptmanager1 runat=server >


<Scripts>
<asp:ScriptReference Path=myScript.js />
<Scripts>
</asp:ScriptManager>

Can aslo load files as embedded resources

ServiceReference

Easy way to access Web Services


using Ajax
Use ServiceReference

Creates a JavaScript proxy class


Sent to client

ScriptManager in Debug
Mode

ScriptManager property
Default value is Auto
Uses debug setting in Web.config
<compilation debug=true />

Options

Auto
Debug
Inherit
Release

Can use debug versions of JavaScript files

UpdatePanel default
behavior

Default behavior is surprisingly powerful

Render mode attribute

UpdateMode attribute

Default block setting renders a div tag


Inline setting renders a span tag
Use with multiple UpdatePanels
Default always causes update any time page refreshes
Conditional setting only updates when specifically updated
Only one request at any time for all UpdatePanels
Force update with UpdatePanels Update Method

ChildrenAsTrigger attribute

Controls whether child control is wired to cause update

Triggers

UpdatePanels capture __dopostback event


and perform updates

Can manipulate this behavior with


AsyncPostBackTrigger
ChildrenAsTriggers set to true by default

All child control that emit postback will cause update

Change Behavior

Set specific control in UpdatePanel to cause full


postback
Control outside UpdatePanel to trigger update

ScriptManagerProxy Control

Use to access ScriptManager control on a


master page from a content page
Makes sense to put ScriptManager on
master page

Then add UpdatePanel on content page


Proxy lets you change properties of master
ScriptManager
Inherit all other settings

Error if use Proxy but master page has no


ScriptManager
Can get a proxy to full Scriptmanager

UpdateProgress Control

Ajax is asynchronous by nature

But can take time for a response

Sends request, doesnt wait for response


Page remains responsive to user
Page should provide indication that
something is happening
Even if it is illusion

Use UpdateProgress control

Timer Control

Update partial page contents at


some interval
Can be highly annoying for entire
page to refresh

Use Ajax to limit extent of update

Timer control makes it easy

Nesting UpdatePanels

Can combine UpdatePanels almost any way


you want
Nest UpdatePanels

Control relationship through UpdateMode attribute


Refreshes child when parent refreshes

Child can refresh independently of parent

Nest as deeply as you wish

Descendents always refresh when ancestor


refreshes

Minimizing Data Transfer with


UpdatePanel

Whole point of UpdatePanel is to minimize data from


server

Implement partial-page postbacks

Where should you locate UpdatePanels?

Identify portion of page that should refresh

Warp smallest possible area: nothing extraneous


Cant wrap incomplete HTML

How will parts of the page refresh relative to each other?


Define conditions that cause a refresh
Then can implement UpdatePanels

Resist temptation to wrap entire page in an UpdatePanel


An art as much as science

Using Page Methods

Server-side Ajax features barely scratch the surface

True Ajax: Closer to the version

Optimal blend of page processing and granularity


Lots of processing on Client and Server
Client-Side Ajax
Javascript on the browser communicates with server
Uses HTTP for precision tool

ASP.Net Ajax Client Library


Two techniques:

Calling a Web service from the browser


Calling a server-side page method

Calling a Server-Side Page


Method

Call a method in pages code-behind


Uses neither a full or partial-page
postback
Counterintuitive

ASP.NET turns method into a Web


service

Ajax History and the Browser


Back Button

With Ajax, browser back and forward


buttons dont work

Browser history works on URLs

Use Ajax History

Gets around the navigation problems


History is not enabled by default
You need to implement page state
Sample: record state for each
Northwind category the user selects

Each time the user selects new product


category, create a history point

Control Extenders

Originally part of an Ajax


documentation site
Control Extender

Add functionality to another control


For example, the
ConfirmButtonExtender
Can Implement confirmation with JavaScript
Or use the extender

Control vs. Extender

Everything in the toolkit is a control

But there are two types of controls


Control: provides client-side
functionality and interacts with user
Extender: aslo a control, but functions as
add-on

Extender always have a


TargetControlID attribute

Server and Client Controls

Two sets of largely duplicate controls,


server and client
Server Control

Add to Web form, use runat=server


Write server-side code to manipulate
Use Ajax Client and jQuery Libraries

Client Controls

Implemented as JavaScript objects


Use in .aspx, .html, .jsp, .php, etc. pages

When use Server or Client


Controls?

Use server controls when:

Use Client controls when:

Want highly interactive Web pages


Dont want to write JavaScript
Want client-side interactivity without server controls
Are okay with writing JavaScript

Focus in this section is on server controls


Ajax Client ToolKit now includes what was the
Ajax Client Library

Add the Ajax Control ToolKit to


the Visual Studio Toolbox

Toolkit ships as a zip file


All controls are in the
AjaxControlToolKit.dll assembly
Easiest to use from Visual Studio
Toolbox

ToolKit Controls and


Extenders

Toolkit has more than 40 controls and


extenders
Plenty of features to make pages
more usable and attractive

AlwaysVisibleControlExtend
er

Web pages can be long

Handy to keep some stuf always in view

Column headers
Menu or command buttons
Keep ad in views

AlwaysVisibleControlExtender anchors a control


within visible portion of browser window

HorizontalSide and VerticalSide properties


Horizontalofset and VerticalOfset properties
TragetControlID property

AutoCompleteExtender
Control

Extends standard textbox control

Makes easier for users to find items in


long list
User starts typing characters
Panel pops-up with matches so far
If desired item appears in list, user can
select and textbox populated with string
value

FilteredTextBoxExtender
Control

Restrict characters user can type in


TextBox
Specify either allowed or forbidden
characters

ListSearchExtender Control

Extends a ListBox or DropDownList to


quickly find items

By default, display in order added list

Regular list: type characters and see


first item with match

Hard to use successfully in a long list

MaskedEditExtender Control

Need to validate user input

Makes it easier for user to provide good data


Prevent some injection attacks

MaskedEditExtender extends TextBox to


define input masks

Control input characters


Provide punctuation as a guide for input

Acts as an input template

Derives from standard ASP.NET validators

TextBoxWaterMarkExtender
Control

With tight space, nice to display info


within empty textboxes

When control gets focus, text disappears


Takes some work to implement with CSS
and JavaScript

TextBoxWaterMarkExtender takes
care of the heavy lifting

One of the simplest and easiest to use

PasswordStrenght Control

Password must have minimum length


and complexity
PasswordStrenght control extends
textbox to display indicator of
strength as user types

Nice way to give instant feedback

ToolkitScriptManager
Control

No additional functionality beyond


script combining

Purely for performance

In addition to ScriptManager
properties

CombineScripts property
CombineScriptsHandlerUrl property

You might also like