ASP.NET 3.5 AJAX Unleashed Editor-in-Chief Copyright © 2009 by Pearson Education,Inc. Karen Gettman All rights reserved. No part of this book shall be reproduced,stored in a retrieval Executive Editor system,or transmitted by any means,electronic,mechanical,photocopying,recording, or otherwise,without written permission from the publisher. No patent liability is Neil Rowe assumed with respect to the use of the information contained herein. Although every Development Editor precaution has been taken in the preparation of this book,the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for Mark Renfrow damages resulting from the use of the information contained herein. Managing Editor ISBN-13: 978-0-672-32973-9 Kristy Hart ISBN-10: 0-672-32973-5 Project Editor Library of Congress Cataloging-in-Publication Data: Meg Shaw Foster,Robert Hill. Copy Editors ASP.NET 3.5 Ajax unleashed / Robert Foster. Lori Lyons p. cm. Karen Annett ISBN 0-672-32973-5 1. Active server pages. 2. Ajax (Web site development technology) 3. Indexer Application software--Development. 4. Microsoft .NET. I. Title. Erika Millen TK5105.8885.A52F67 2008 Proofreader 005.2'76––dc22 2008014763 Anne Goebel Technical Editor Printed in the United States of America Todd Meister First Printing December 2008 Publishing Trademarks Coordinator All terms mentioned in this book that are known to be trademarks or service marks Cindy Teeters have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the Book Designer validity of any trademark or service mark. Gary Adair Warning and Disclaimer Composition Every effort has been made to make this book as complete and as accurate as Jake McFarland possible,but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to Manufacturing Buyer any person or entity with respect to any loss or damages arising from the information Dan Uhrig contained in this book or programs accompanying it. Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information,please contact U.S. Corporate and Government Sales 1-800-382-3419 [email protected] For sales outside of the U.S.,please contact International Sales [email protected] Introduction A s an ASP.NET web developer in today’s market, you need countless skills to distinguish your- self from the next person. One of those skills that you can quickly acquire is developing AJAX- enabled applications. As your users begin to utilize AJAX-enabled sites on the web, such as Live.com and Google Maps, they are beginning to expect the same rich functionality in the applications that you deliver. Although these applications took many man hours to create, the process is made easier for you as a developer with the AJAX library that’s packaged with ASP.NET 3.5. You can save many hours and lines of code by learning and leveraging ASP.NET AJAX to create and deliver a very rich user experience in your applications. In this book, you learn how to make the most of ASP.NET AJAX by building on the knowledge that you already have as an ASP.NET developer and extend that knowledge so that you can easily create AJAX-enabled applications. The book has been divided into the following chapters: Chapter 1—Introduction to AJAX Technologies In this chapter, you learn the fundamentals of AJAX by first understanding the XmlHttpRequest JavaScript object, and then building a simple AJAX library for use in your applications. Chapter 2—Introduction to ASP.NET AJAX Chapter2introducesyoutothecontrolsandcapabilitiesthatareavailableinASP.NETAJAXand servesasaspringboardfortechnologiesthatarediscussedinfuturechapters. Chapter 3—The ScriptManager and ScriptManagerProxy Controls Chapter 3discusses the core object of the ASP.NET AJAX library: the ScriptManager control. In this chapter, you learn the capabilities of the ScriptManager control and how you can best utilize it in your AJAX-enabled pages. Chapter 4—The ASP.NET AJAX Client API In Chapter 4, you learn how to make the most of the ASP.NET AJAX client-side objects that are made available via the ScriptManager control. Chapter 5—The UpdatePanel and Timer Controls In Chapter 5, you learn how to use the UpdatePanel control to quickly and easily add AJAX func- tionality to your ASP.NET web pages. You also learn how to use the Timer control to make asyn- chronous callbacks from your pages at a specified time interval. 2 Introduction Chapter 6—Advanced Techniques with the ASP.NET AJAX PageRequestManagerObject In Chapter 6, you learn some essential techniques that can be used with the ASP.NET AJAXPageRequestManagerobject to save you many lines of code as well as help you create richer user experiences for your AJAX-enabled applications. Chapter 7—Using the ASP.NET AJAX Control Toolkit In Chapter 7, you learn about the controls that are available in the ASP.NET AJAX Control Toolkit, which is an open-source, community-based suite of controls for ASP.NET AJAX. Chapter 8—Building an ASP.NET AJAX Extender Control Chapter 8first introduces the concept of creating AJAX-enabled extender controls, and then shows you how to build an extender control that can be used in your applications. Chapter 9—ASP.NET AJAX and SharePoint 2007 In Chapter 9, you learn how to enable ASP.NET AJAX in SharePoint 2007 and Windows SharePoint Services (WSS) 3.0, and then you learn how to build an AJAX-enabled WSS web part. Chapter 10—Creating ASP.NET AJAX-Enabled Vista Sidebar Gadgets In Chapter 10, you learn how to build ASP.NET AJAX-Enabled Gadgets for the Windows Vista Sidebar. 1 CHAPTER IN THIS CHAPTER . AJAX and Web 2.0 Introduction to AJAX . Why Use AJAX? Technologies . AJAX: An Example . Using the AJAX Library I f you’ve purchased this book, you probably are interested in AJAX technologies. If you are not familiar with the tech- nology or are new to AJAX, it is important that you take some time and understand where AJAX fits into the big picture of web development. This section helps bring you up to speed with AJAX’s place in your web development toolbox. One problem with the design of web pages (especially ASP.NET web pages) is that to refresh the data on the page, it must postback to the server. This causes the page to flicker while the page is posting, and then the page is reloaded in the browser with the results of the post. You can view the amount of data with tools such as IEHTTPHeaders and HTTPWatch. You will quickly notice that the amount of information getting posted is quite size- able because ASP.NET applications not only postback the controls, but also post the page’s ViewState. Although the technique of a postback works, it creates a lot of traffic over the wire and inherently reduces the overall scalability of your application. Asynchronous JavaScript and XML (AJAX)is a development pattern that you can use to provide your users with a much richer user experience in your web applications. Simply stated, AJAX allows you to asynchronously load data into pieces of a page on demand instead of loading the whole page each time data is requested. An example of where a user experience can be enhanced by AJAX is a web page that contains related dropdown boxes. For example, say that you have a web page that supplies information on cars in which a user must select the year, make, and model of his car from dropdown boxes on the 6 CHAPTER 1 Introduction to AJAX Technologies page. When a user selects a year, she populates all makes for a selected year in the make dropdown box. Additionally, when a user selects a make of car, the models dropdown is populated with models for a given year and make. If you use traditional ASP.NET without AJAX, you will probably set the AutoPostBack property of your dropdowns to true and the page will postback (and flicker) when your user makes selections on the page. Conversely,ifyouuseAJAX,datacanbeloadedasynchronouslyintothelistboxesasthe usermakesselectionsonthepage.Thisismuchmoreefficientbecauseonlythedatabeing requestedwilltravelintherequesttotheserver,whichcouldbeassimpleasaquerystring appendedtotheendofapagerequest.Also,thepagewillnotflickerastheusermakes selectionsinthedropdownsbecausethepostactuallyishappeninginthebackground. NOTE An example of AJAX is described later in the chapter. AJAX and Web 2.0 Web 2.0 is a term (or rather buzzword) that you often hear when describing most “modern” web sites; however, it shouldn’t be a new concept to web developers. Web 2.0 is actually a consolidation of many existing technologies that allows you to provide a rich interactive user experience over the web. Examples of Web 2.0 technologies include, but aren’t limited to, the following areas: . RichInternetApplications(RIAs),whichincludeAJAX,AdobeFlash,Silverlight,and Moonlight . Web services . Blogs . Wikis . Social networking . Social bookmarking . RSS/Atom Before the Web 2.0 movement began on the Internet, web pages often focused solely on providing the user with data. The user would simply request a page, view the page, request another page, view that page, and so on. In contrast, the patterns and techniques behind Web 2.0 are all about the user experience with the web: AJAX and web services for rich, efficient user experiences, blogs, wikis, social networking, and social bookmarking for collaboration, and RSS/Atom so that users can “subscribe” to data. Why Use AJAX? 7 As technologies such as AJAX evolve and are adopted in large scale on the web, Web 2.0 techniques are quickly becoming the expected user experience for the web. Mainstream examples of AJAX include the Google-based applications, such as Google’s Maps, Docs, 1 and Calendar, as well as Microsoft-based applications, such as Hotmail, and Windows Live-based applications. As users start utilizing these types of applications in their every- day lives, they will come to expect the same type of functionality in the applications you develop. Why Use AJAX? Asstatedpreviouslyinthischapter,youcanuseAJAXtohelpprovidearichuserexperi- ence.Ofallthenew,cooltechniquesandtechnologiesthatareavailableinWeb2.0and richInternetapplications,AJAXisclearlythemostwidelyusedtoday.Shouldyouuse AJAXsimplybecauseit’scool?Theshortansweris“No,”whichisexplainedinthenext section. AJAX Rationale Although the user experience that results from AJAX development patterns is a much richer experience, the rationale for utilizing AJAX is the total amount of traffic that is reduced from users accessing your web pages. When you have a web application with a large user base, using AJAX significantly increases the scalability of the application due to the amount of web traffic that is reduced every time a page is loaded. The following list gives advantages and disadvantages of AJAX: Advantages . Reduced page bandwidth . Load page data on demand . Service-based approach to web development . Rich user experience Disadvantages . Unexpected browser functionality (when the user clicks the back or refresh button) . Business logic can exist in the JavaScript . Difficult to test with automated tools Although this book highlights and focuses on the advantages of AJAX, several disadvan- tages should be noted. The first thing your users will notice is that when they click the refresh or back button in the browser, the page has a possibility of losing its state when the page reloads. This is a result of dynamically loading data on demand (which was one of the advantages of AJAX). 8 CHAPTER 1 Introduction to AJAX Technologies The second disadvantage of AJAX that you will see in the development world is actually JavaScript. You might wonder that if AJAX is initiated from client-side JavaScript, how can JavaScript be a disadvantage? The answer is that JavaScript eventually will be considered a disadvantage for AJAX in your web applications. Over time, you will be quite shocked at the amount of JavaScript that is required (which is an evolution throughout the lifecycle of your application) for AJAX functionality in your application. It will start out very small and clean, but can quickly spiral out of control. From the architecture perspective, there is not a clean way to reverse-engineer JavaScript into an architecture model. An architecture document will probably define how a page should function, and there could be thousands of lines of JavaScript behind the scenes to enable this functionality. Depending on your environment and Software Development Lifecycle (SDLC), this could become a problem because it is very difficult to validate the JavaScript against the architecture models. The third (and certainly not the last) disadvantage is the potential difficulty of testing AJAX functionality with automated tools. For example, Visual Studio Team Suite (VSTS) 2005 had limited support for AJAX when creating web tests. This problem was easily circumvented with tools such as Fiddler(http://www.fiddlertool.com/fiddler/), which helps you capture AJAX requests, which then can be loaded into the VSTS Web Test. It is important to note that these issues have been resolved in VSTS 2008. This section is designed not to scare you away from AJAX, but to create an awareness of things that can affect you and your AJAX development experience. Best practices and warnings are highlighted in upcoming chapters so that you can be aware of the pitfalls that can show up in your applications. In the next section, you learn the basics of implementing AJAX in your applications. AJAX: An Example Now that you understand the advantages and disadvantages of AJAX, it is helpful to learn about the code behind AJAX requests. This section introduces an example of using AJAX and JavaScript Object Notation (JSON). The XMLHttpRequest Object Themain object behind AJAX is the XMLHttpRequestobject. This object exposes function- ality that allows you to send and receive data (usually XML-based, but not required) from client-side JavaScript code to a server page. XMLHttpRequesthas six methods, listed in Table 1.1, and seven properties, listed in Table 1.2. Deep knowledge of the capabilities of the XMLHttpRequestobject’s properties and methods is required learning for any AJAX developer. At its core, every library that encapsulates AJAX functionality (ASP.NET AJAX, AJAX.NET, Yahoo YUI, and so on) uses the XMLHttpRequestobject. AJAX: An Example 9 The next section defines a simple AJAX JavaScript library that can be used to make AJAX calls in your web applications. 1 TABLE 1.1 XMLHttpRequestMethods Method Parameters Description Abort Abortsthe request that has been made. getAllResponseHeaders Returns a string of all response headers. getResponseHeader headerName Returnsthe value of a given response header. Open method,url Opens the request to a method,url,async specified URL. method,url,async, methoddefines the HTTP method that will be used username (typically GET or POST). method,url,async, username,password urldefines the location of the page that is being requested. asyncis a Boolean that defines whether the request will be made asynchronously or not. Send content Sendsthe request to the server. DOMString Document DOMStringis the XML that is to be sent as a string. Documentis an XML DOM document setRequestHeader label, value Allowsyou to add a label and value to the HTTP header that is being sent to the server. 10 CHAPTER 1 Introduction to AJAX Technologies TABLE 1.2 XMLHttpRequestProperties Property Description onreadyStatechange Eventhandler that is fired when the readyStateproperty changes. This will be a JavaScript function that handles the data that is returned to the client. readyState Returnsthe state of the XMLHttpRequestobject. Possible values are 0 = not initialized 1 = open 2 = HTTP Headers received 3 = receiving 4 = loaded responseText Returns the complete response as a string. responseXML Returns the complete response (if it is XML) as an XML docu- ment object. responseBody Returnsa binary encoded string of the response. Status Returns the HTTP status code of the request. HTTP status codes are defined at http://www.w3.org/Protocols/rfc2616/ rfc2616-sec10.html. statusText Returns the HTTP status description of the request. A Simple AJAX Library As adeveloper, you probably have several (possibly hundreds of) scripts stuffed away somewhere that you reuse to accomplish specific tasks. One such script you can use for making AJAX calls is provided in Listings 1.1through 1.3. NOTE Although this library can be written many different ways,this example contains three JavaScript functions: createAjaxRequest,createHttpRequestObject,and getResponse. Each function is separated into its own listing and described in the next three sections. LISTING 1.1 createAjaxRequestFunction //Section 1 var http_request = false; function createAjaxRequest(url, parameters) {
Description: