1 designing & developing web- based solutions in asp.net week 6 javascript & ajax

49
1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

Upload: dwayne-smith

Post on 27-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

1

Designing & Developing Web-Based Solutions in ASP.NET

Week 6

JavaScript & AJAX

Page 2: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

Today’s Agenda

JavaScript Language Overview What, Why, Where, When, How

AJAX & ASP.NET AJAX Callbacks Comparison AJAX Web Services AJAX Controls

Lab: Play with JavaScript Build AJAX Web Services in different ways

Designing & Developing Web-Based Solutions in ASP.NET 2

Page 3: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

What is JavaScript?

Java == JavaScript?NO!!!

Original Name = ECMAScript European Computer Manufacturers Association

Created by Netscape

First used in 1996 (Netscape & IE)

Designing & Developing Web-Based Solutions in ASP.NET 3

Page 4: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

Why JavaScript?

Read / Write HTML in browser

React to events

Client side validation

Read / Write cookies

Detect Browser

Designing & Developing Web-Based Solutions in ASP.NET 4

Page 5: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JavaScript – Placement

Embedded anywhere within < html ></html> Attribute to an HTML tag:

<body onunload="alert('Thanks for visiting');"> In a <script> tag (unlimited tags)

Executed on load:

<script>alert(‘Greetings');</script> Executed when function called:

<script>function Greet { alert(‘Greetings') ;}</script>

Download a .js script file from a server:<script type="text/javascript" src=“URL/MyScript.js"></script>

Designing & Developing Web-Based Solutions in ASP.NET 5

Page 6: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JavaScript – Order of Execution

Top to Bottom of page Caution:

“Execute in Place” script must occur after elements it modifies.

Designing & Developing Web-Based Solutions in ASP.NET 6

Page 7: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JavaScript - Compatibility

Comments hide script for non-java browsers

<script type=“text/javascript”><!- -

Window.alert(‘This browser supports JS’);

// - - >

</script> Other comment styles, same as C

/* code block */ // single line

Designing & Developing Web-Based Solutions in ASP.NET 7

Page 8: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS – Language Basics

Case Sensitive Memory Managed 16 bit Unicode strings

Designing & Developing Web-Based Solutions in ASP.NET 8

Page 9: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS - Variables

Generic Type “var” var mytext = ‘some text’; var x = 5; var myObj = new XmlHttpRequest();

Specific Types int, float, byte, double, char, short, boolean More…

Auto Declaration if not previous defined y = 10;

Redefinition does not clear var x; // still equals 5

Designing & Developing Web-Based Solutions in ASP.NET 9

Page 10: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS – Variable Scope

Global to page (page shares all script space)<script id=“block1”> var a=1; </script>

<script id=“block2”> var b=2; </script>

<script id=“block3”> var c=a+b; </script>

Local to functionfunction First() { var x=1; }

function Second() { var y=2; }

function Third() { var z= x+y; } // SCOPE ERROR

No Block Scope { {var inSecondBlock = 1;}

Designing & Developing Web-Based Solutions in ASP.NET 10

Page 11: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS - Arrays

Yes, but not really. More like a Vector ADT Automatically increases in size Mixed type elements

var myArray = [ ‘mystring’, 5, null, 1.8, true ] Single dimension, but can have arrays of arrays

var two_d = [ [ 1, 2, 3], [4, 5, 6] ]; two_d[1][1] // === 5

Designing & Developing Web-Based Solutions in ASP.NET 11

Page 12: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS - Objects

No class definition, only Object Literals var person = {

ssn: 555123333,

name: {

first: “Joe”,

last: “Cool”

} };

Retrival person.name.first person[“ssn”]

Designing & Developing Web-Based Solutions in ASP.NET 12

Page 13: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS - Objects

Augmentationperson.address = “1234 Mocking Bird Lane”; person object augmented with “address” property.

Deletedelete person.ssn; “ssn” property removed from object.

Passed by Reference Never copied

Designing & Developing Web-Based Solutions in ASP.NET 13

Page 14: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS – Comparison, == vs ===

== // is equal to === // value and type equal

Given that z=3;

z == 3 // true

z == “3” // true

z === 3 // true

z === “3” // false

Designing & Developing Web-Based Solutions in ASP.NET 14

Page 15: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JS – Popup’s

alert(“hello world”);

var result = confirm(“Press OK or Cancel”);

var result = prompt(“How old are you?”, “Enter age”);

Designing & Developing Web-Based Solutions in ASP.NET 15

Page 16: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JavaScript – Common Events

Event Trigger

onchange Change check/radio or leave textbox

onclick, ondblclick Click on button or in area

onmouseover, onmouseout Mouse enter/exit region

onkeyup, onkeydown Keypress within focused control

onselect Text selection

onfocus, onblur Control receives/loses input focus

onabort, onerror Image download canceled/errored

onload Page completely downloaded

onunload Before new page downloaded

Designing & Developing Web-Based Solutions in ASP.NET 16

Page 17: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

DOM and DHTML

Interact with web page as tree of xml objects DHTML = “Dynamic HTML” JavaScript + DOM

The Document Objectvar label = document.getElementById(“LabelOne”);

label.innerText = “text changed in script”;

Designing & Developing Web-Based Solutions in ASP.NET 17

Page 18: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

DOM - Object PropertiesMethod Description Sample

innerHTML HTML between begin & end tags

label.innerHTML = “some text”;// OUTPUT<div>some text</div>

style CSS properties Label.style.fontSize = “10”;

value Controls value attribute

Label.value = “set the text”;Checkbox.value = “true”;

tagName HTML tag name myDiv.tagName == “Div”

parentElement Parent Object Var myDiv = label.parentElementmyDiv.style.backgroundColor = “blue”;

Designing & Developing Web-Based Solutions in ASP.NET 18

Page 19: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

document.* Collections

document.anchors[] document.images[] document.links[]

Designing & Developing Web-Based Solutions in ASP.NET 19

Page 20: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

document.* Properties

cookie domain lastModified readyState referrer title URL

Designing & Developing Web-Based Solutions in ASP.NET 20

Page 21: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

document.* Methods

close() getElementById() getLementsByName() getElementsByTagName() open() write() writeln()

Designing & Developing Web-Based Solutions in ASP.NET 21

Page 22: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

Browser DOM Objects

Window // open browser window info History // Sites Visted Location // Current URL info

Navigator // Browser Info Screen // Display mode info

Designing & Developing Web-Based Solutions in ASP.NET 22

Page 23: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

HTML DOM Objects

Document // The currently loaded HTML Anchor Button Image Body Form Table one fore each element type…

Designing & Developing Web-Based Solutions in ASP.NET 23

Page 24: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

JavaScript – Reference

Good Reference & Samples sites www.W3Schools.com Microsoft – MSDN CodeProject

DOM http://www.w3schools.com/HTMLDOM/dom_reference.asp

JavaScript http://www.w3schools.com/jsref/default.asp

Designing & Developing Web-Based Solutions in ASP.NET 24

Page 25: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

Lab – CodeProject Samples

Vote

Paint

Designing & Developing Web-Based Solutions in ASP.NET 25

Page 26: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

26

Designing & Developing Web-Based Solutions in ASP.NET

AJAX

Page 27: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX - Introduction

Acronym Asynchronous JavaScript and XML Correction: Communicates a string, not always XML

Biggest Issue = Browser Compatibility

Uses JavaScript to communicate to server Does not cause a page refresh Uses DOM to update HTML of current page

Designing & Developing Web-Based Solutions in ASP.NET 27

Page 28: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – 2 Step Process

Request JavaScript sends request to Server

XMLHttpRequest

Response Browser routes server response to script

function myResponseFunction()

Designing & Developing Web-Based Solutions in ASP.NET 28

Page 29: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – XMLHttpRequest()

The cornerstone of AJAXvar req = new XMLHttpRequest(); // ActiveX for older

Set Location & protocol req.open( < GET,POST,PUT >, url)

Set JavaScript function as Callback req.onreadystatechange = myCallback;

Send request req.send()

Designing & Developing Web-Based Solutions in ASP.NET 29

Page 30: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – The Request

<script>

Var request; // will also use this variable in callback

function getMyData()

{ request = new XMLHttpRequest();

request.open(“GET”, “UpdateData.ashx”);

request.onreadystatechange = myCallback;

request.send();

}

</script>

Designing & Developing Web-Based Solutions in ASP.NET 30

Page 31: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – Server’s HTTP Handler

File APP_Code / UpdateData.ashx public class UpdateData : IHttpHandler {

public void ProcessRequest( HttpContext context) {

context.Response.Write(“Hi from the server”); }

public bool IsReusable // keep handler loaded or discard {get{ return true;}}

}

Designing & Developing Web-Based Solutions in ASP.NET 31

Page 32: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – The Callback

// Use original “var request;” from caller<script>

function myCallback()

{

if(request.status == 200) // check for pass/fail

{

var txt = request.responseText;

}

}

</script>

Designing & Developing Web-Based Solutions in ASP.NET 32

Page 33: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – HTTP Handler Setup

Described in Chapter 5 – ASP.NET Applications

Simple Approach Add .ashx file to App_Code folder Register Handler in web.config

<system.web>

<httpHandlers><add verb=“Get” // GET,PUT,POST or *

path=“UpdateData.ashx” // filename

Type=“UpdateData”> // namespace.ClassName

Designing & Developing Web-Based Solutions in ASP.NET 33

Page 34: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – Client Callbacks

Yet another way Server Differences

Public partial class ClientCallback : System.Web.UI.Page, ICallbackEventHandler

Doesn’t use IHttpHandler Server callback can be in page’s code-behind.cs

Client doesn’t need to call XMLHttpRequest ASP.Net handles XMLHttpRequest Must register callbacks in the servers Page_Load() JavaScript Callback now contains 2 parameters

Designing & Developing Web-Based Solutions in ASP.NET 34

Page 35: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX –Server Callback

Server ModificationsPublic partial class ClientCallback :

System.Web.UI.Page, ICallbackEventHandler

{Public void Page_Load(…)

{

String myScriptcallback =Page.ClientScript.GetCallbackEventReference(

This, “document.getElementById(‘myLable’).value,

clientUpdateDataCB, “null”, true);

myLabel.Attributes[“onchange”] = myScriptcallback;

}

}Designing & Developing Web-Based Solutions in ASP.NET 35

Page 36: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – Client Changes

Callback has parameters Doesn’t use the XMLHttpRequest

function clientUpdateDataCB(result, context)

{var text = result;

Window.alert(text);

}

Designing & Developing Web-Based Solutions in ASP.NET 36

Page 37: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

37

Designing & Developing Web-Based Solutions in ASP.NET

ASP.NET AJAX

(Formerly Known as “Atlas”)

Page 38: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

ASP.NET AJAX – Comparison

Simplified client-server communication Uses WebService protocol. Handles data serialization (no more “all data in a string”)

Typed data Server send client typed data JavaScript extensions add Object Oriented features to script.

Premade AJAX Tools Extensions (UpdatePanel, Timer, Update Progress) Toolkit

Controls Control Extenders

Designing & Developing Web-Based Solutions in ASP.NET 38

Page 39: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – Creating Web Service

Add new item Web Service Creates

Current folder: MyWebService.asmx App_Code folder: MyWebService.cs

Designing & Developing Web-Based Solutions in ASP.NET 39

Page 40: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – Web Service (.asmx)

.asmx locates the code page .cs contains the actual Web Service

[WebService(Namespace = "http://tempuri.org/")] // Uncomment for AJAX “JSON” service // [System.Web.Script.Services.ScriptService] public class AJAXWebService : WebService {

[WebMethod] public string HelloWorld() { return "Hello World“; }

}

Designing & Developing Web-Based Solutions in ASP.NET 40

Page 41: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – Client Setup

Add new item AJAX web form Creates normal web form in current directory:

WebPage.cs WebPage.aspx

Automatically Adds: <asp:ScriptManager />

OR

Add new item Web form Then manually add <asp:ScriptManager> to .aspx

Designing & Developing Web-Based Solutions in ASP.NET 41

Page 42: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – ScriptManager

Add web service reference Must live inside <form>

<form><asp:ScriptManager ID=“ScriptMgr" runat="server“>

<Services><asp:ServiceReference

Path="~/Projects/Samples/…/AJAXWebService.asmx" />

</Services>

</asp:ScriptManager> </form>

Designing & Developing Web-Based Solutions in ASP.NET 42

Page 43: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – The Client Call

Add a control to page Add callback to control

JavaScript function call <asp:input … onclick=“LocalCallHelloWorld();“/>

or Embedded JavaScript

<asp:input … onclick=

“AJAXWebService.HelloWorld(OnResponse, OnErr);“/>

Designing & Developing Web-Based Solutions in ASP.NET 43

Page 44: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – In Page Web Service

<ScriptManager EnablePageMethods=“true”>

public partial class AJAXWebService : Page {

[WebMethod()]

[ScriptMethod()]

Public static HelloWorld(){ return “Hello World”}}

PageMethods.HelloWorld(OnResponse, OnErr);

Designing & Developing Web-Based Solutions in ASP.NET 44

Page 45: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

<asp:Button> - Special Case

<asp:Button onclick=“ServerOnlyMethod"> onclick attribute defined by <asp:Button>

Normally JavaScript Events pass-through (onblur, onclick,…)

Alternative OnClientClick=“SomeJavaScript()” Also does postback Work Around

<asp:Button OnClientClick=“return MyFunc();” />

function MyFunc{ … return false;}

Designing & Developing Web-Based Solutions in ASP.NET 45

Page 46: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – UpdatePanel

Must use <asp:ScriptManager> Updates all UpdatePanels

Ignores controls not in an update panel Set UpdateMode=“Conditional” to NOT update all

panels.

<asp:UpdatePanel> <ContentTemplate>

<asp:Label/> …

Designing & Developing Web-Based Solutions in ASP.NET 46

Page 47: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

AJAX – UpdatePanel Triggers

Triggers Allow

Controls outside UpdatePanel to cause update

Inner controls to cause conditional updates.

Designing & Developing Web-Based Solutions in ASP.NET 47

Page 48: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

Next Week

Another callback mechanism WCF web service (MS preferred way)

Another DOM parser for JavaScript jQuery

More premade AJAX controls AJAX Toolkit

Designing & Developing Web-Based Solutions in ASP.NET 48

Page 49: 1 Designing & Developing Web- Based Solutions in ASP.NET Week 6 JavaScript & AJAX

Lab – ASP.NET AJAX

Build a Web Service Button Sample Convert to PageMethod

Use an UpdatePanel

Designing & Developing Web-Based Solutions in ASP.NET 49