1 / 49

Designing & Developing Web-Based Solutions in ASP.NET

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

jaunie
Download Presentation

Designing & Developing Web-Based Solutions in ASP.NET

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. JS – Language Basics Case Sensitive Memory Managed 16 bit Unicode strings Designing & Developing Web-Based Solutions in ASP.NET

  9. JS - Variables • Generic Type “var” • varmytext = ‘some text’; • var x = 5; • varmyObj = 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

  10. JS – Variable Scope • Global to page (page shares all script space) <script id=“block1”> var a=1; </script> <script id=“block2”>varb=2; </script> <script id=“block3”>varc=a+b; </script> • Local to function function First() {var x=1; } function Second() { var y=2; } function Third() {var z= x+y; } // SCOPE ERROR • No Block Scope • { {varinSecondBlock = 1;} Designing & Developing Web-Based Solutions in ASP.NET

  11. JS - Arrays • Yes, but not really. More like a Vector ADT • Automatically increases in size • Mixed type elements • varmyArray = [ ‘mystring’, 5, null, 1.8, true ] • Single dimension, but can have arrays of arrays • vartwo_d = [ [ 1, 2, 3], [4, 5, 6] ]; • two_d[1][1] // === 5 Designing & Developing Web-Based Solutions in ASP.NET

  12. 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

  13. JS - Objects • Augmentation person.address = “1234 Mocking Bird Lane”; • person object augmented with “address” property. • Delete delete person.ssn; • “ssn” property removed from object. • Passed by Reference • Never copied Designing & Developing Web-Based Solutions in ASP.NET

  14. 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

  15. 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

  16. JavaScript – Common Events Designing & Developing Web-Based Solutions in ASP.NET

  17. DOM and DHTML • Interact with web page as tree of xml objects • DHTML = “Dynamic HTML” JavaScript + DOM • The Document Object var label = document.getElementById(“LabelOne”); label.innerText = “text changed in script”; Designing & Developing Web-Based Solutions in ASP.NET

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

  19. document.*Collections document.anchors[] document.images[] document.links[] Designing & Developing Web-Based Solutions in ASP.NET

  20. document.* Properties cookie domain lastModified readyState referrer title URL Designing & Developing Web-Based Solutions in ASP.NET

  21. document.* Methods close() getElementById() getLementsByName() getElementsByTagName() open() write() writeln() Designing & Developing Web-Based Solutions in ASP.NET

  22. 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

  23. 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

  24. 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

  25. Lab – CodeProject Samples • Vote • Paint Designing & Developing Web-Based Solutions in ASP.NET

  26. Designing & Developing Web-Based Solutions in ASP.NET AJAX

  27. 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

  28. 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

  29. AJAX – XMLHttpRequest() • The cornerstone of AJAX varreq= 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

  30. 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

  31. 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 boolIsReusable // keep handler loaded or discard • {get{ return true;}} • } Designing & Developing Web-Based Solutions in ASP.NET

  32. 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

  33. 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

  34. 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

  35. AJAX –Server Callback • Server Modifications Public 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

  36. 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

  37. Designing & Developing Web-Based Solutions in ASP.NET ASP.NET AJAX (Formerly Known as “Atlas”)

  38. 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

  39. 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

  40. 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

  41. 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

  42. 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

  43. 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

  44. AJAX – In Page Web Service • <ScriptManagerEnablePageMethods=“true”> public partial class AJAXWebService : Page { [WebMethod()] [ScriptMethod()] Public staticHelloWorld(){ return “Hello World”} } • PageMethods.HelloWorld(OnResponse, OnErr); Designing & Developing Web-Based Solutions in ASP.NET

  45. <asp:Button> - Special Case • <asp:Buttononclick=“ServerOnlyMethod"> • onclick attribute defined by <asp:Button> • Normally JavaScript Events pass-through (onblur, onclick,…) • Alternative • OnClientClick=“SomeJavaScript()” • Also does postback • Work Around <asp:ButtonOnClientClick=“returnMyFunc();” /> function MyFunc{ … return false;} Designing & Developing Web-Based Solutions in ASP.NET

  46. 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

  47. 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

  48. 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

  49. Lab – ASP.NET AJAX • Build a Web Service • Button Sample • Convert to PageMethod • Use an UpdatePanel Designing & Developing Web-Based Solutions in ASP.NET

More Related