Your SlideShare is downloading. ×
LVSOnline Class - Lesson 1
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

LVSOnline Class - Lesson 1


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. AJAX Web Development with ASP.NET – Lesson 1 Instructor: Frank Stepanski Overview Ajax allows you to update parts of your website without refreshing the entire page giving your web visitors a more pleasing web experience. Many web technologies use Ajax; and ASP.NET is just one of them. The components of Ajax are the same no matter what technology you use, but with ASP.NET AJAX you can use the power of server-side controls to dramatically reduce the amount of coding. Microsoft has its own JavaScript framework which handles the client interaction of the browser as well. This library can be accessed with JavaScript code in an ASP.NET page as well. Audience for this Class This class is an “intermediate” level class, so I will assume you have taken my Beginning Web Development with ASP.NET and Intermediate Web Development with ASP.NET which will give you a very good understanding of how to use ASP.NET and C# or have existing knowledge and experience. Even though, I will be covering ASP.NET with Ajax, Ajax is dependant on JavaScript on the client so having an understanding of JavaScript would be helpful as well. You should be able to grasp the JavaScript that is covered in this class even if you have no experience in JavaScript. If you wish to learn more JavaScript you can take one of my JavaScript classes (depending on your skill level): JavaScript Basics and JavaScript Intermediate: Unobtrusive JavaScript Programming. Also, if you haven’t already used ASP.NET with databases, you may want to take my ASP.NET Database Web Developement class since many ASP.NET web sites are using a database for some or even all of their content to provide more interactive and customizable content for their site visitors. Ajax can be used very easily with database- driven web sites to dramatically improve the user experience. LVSOnline - Where Learning is Fun! 1 of 17 Author: Frank Stepanski
  • 2. Tools Used You will be using the free tool of Visual Web Developer Express 2008 for this class. You can also use Visual Studio 2008, which is the commercial version of this free tool. Other Requirements For a weekly review of your assignments, I will allow you to post your weekly assignments as a .zip file, if you do not have a web host that supports ASP.NET AJAX. If you wish to also post your assignments online, the cheapest web host that supports this would be GoDaddy (economy plan – Windows) for $4.99 a month for a three month plan (no yearly contract). If you do not have any web host, a free web host can be provided to FTP your .zip files. Beyond ASP.NET ASP.NET is a server-side technology for building web applications. Almost all the work happens on the web server and not the web browser. Whenever you perform an action in an ASP.NET page—such as clicking a button or sorting a GridView—the entire page must be posted back to the web server. Any significant action on a page results in a postback. If you think about it, this is incredibly inefficient. When you perform a postback in an ASP.NET page, the entire page must be transported across the Internet from browser to server. Next, the .NET class that corresponds to the page must re-render the entire page again from scratch. Finally, the finished page must be sent back across the Internet to the browser. This whole long, slow, agonizing process must occur even if you are updating a tiny section of the page. Using a server-side technology such as ASP.NET usually results in a bad user experience. Every time a user performs some action on a page, the universe temporarily freezes. LVSOnline - Where Learning is Fun! 2 of 17 Author: Frank Stepanski
  • 3. Whenever you perform a postback, the browser locks, the page jumps, and the user must wait patiently, twiddling his thumbs, while the page gets reconstructed. All of us have grown accustomed to this awful user experience. However, we would never design our desktop applications in the same way. When the members of the ASP.NET team invented ASP.NET in the late 1990s, there was good reason to embrace the server-side. Getting a page that was written in JavaScript to work consistently across different browsers, and even across different versions of the same browser was very difficult. The server side was safe and reliable. Web developers are discovering that if they want to build truly great applications, they need to leave the safety of the server side and enter the wilds of the client side. Google has hacked out a path for us by creating several proof-of-concept web applications that demonstrate that you can build reliable, user-friendly, web applications that execute entirely in the browser without the need for postbacks. [See: Google Maps, Google Docs, Google Suggest and Google Gmail] What is Ajax? Ajax is a blanket term. The term Ajax was coined by Jesse James Garrett back in 2005, primarily as a cool way to sell a set of technologies and a new approach to web development. Ajax refers to using a set of specific browser technologies to build web pages. None of these technologies are new and consist of three main components: XMLHttpRequest, DOM and JavaScript. Especially with the advent of ASP.NET, the world of web programming has been simplified. Frameworks offer a think layer of abstraction over basic HTML and HTTP interaction, and the ASP.NET development environment makes it easy with automated code generation and remote debugging. An Ajax application (Figure 1), is a client-side web application written using native browser technologies such as JavaScript and the DOM. A pure Ajax application is a web application that consists of a single page and performs all its communications with the web server through web service calls. LVSOnline - Where Learning is Fun! 3 of 17 Author: Frank Stepanski
  • 4. Unlike a server-side web application, an Ajax application can be very responsive to user interaction. If a user clicks a button in a server-side web application, the button Click event doesn’t actually happen until the page gets posted back to the server. In a client-side Ajax application, on the other hand, the button Click event happens when it happens: right on the browser. In an Ajax application, the user interface layer is located in the browser (where it should be). The business logic and data access layers are located on the server. The user interface layer accesses the business logic layer through web services. Figure 1 – Ajax Application components Components of Ajax LVSOnline - Where Learning is Fun! 4 of 17 Author: Frank Stepanski
  • 5. Ajax is dependent upon a few technologies in order for it to work. The first is the XMLHttpRequest object. This object allows the browser communicate to a back-end server and has been available in the Microsoft world since Internet Explorer 5 through the MSXML ActiveX component. The XMLHttpRequest object allows script code to send HTTP requests and handle their responses. This object is scripted from the client JavaScript code, and with regard to the browser operates asynchronously Support for the XMLHttpRequest object gives JavaScript functions within the client script library the capability to call server-side events. As stated, typically HTTP requests are issued by a browser. It is also the browser that takes care of processing the response that comes from the server and then usually regenerates the entire Web page in the browser after a response is issued. If you use the XMLHttpRequest object from your JavaScript library, you do not actually issue full page requests from the browser. Instead, you use a client-side script engine (which is basically a JavaScript function) to initiate the request and also to receive the response. Because you are also not issuing a request and response to deal with the entire web page, you can skip a lot of the page processing because it is not needed. Of course, the other major component is JavaScript. This technology provides the client- side initiation to communicate with the back-end services and takes care of packaging a message to send to any server-side services. Another aspect of Ajax is support for DHTML and the Document Object Model (DOM). The DOM is a platform independent and language neutral representation on the contents of a web page that scripts can access and use to modify the content, structure, and style of the document These are the pieces that will change the page when the asynchronous response is received from the server. Finally, the last piece is the data that is being transferred from the client to the server. This is done in XML or, more important, JSON. LVSOnline - Where Learning is Fun! 5 of 17 Author: Frank Stepanski
  • 6. Adding Ajax Capabilities Most web sites today might be significantly improved in terms of usability and user experience with a touch of Ajax. As mentioned already, the core of the Ajax model is an internal browser object and the DOM. The interface of both is defined according to standards --- still a de facto standard for XMLHttpRequest and an official W3C standard for the DOM. So this means you can add Ajax capabilities to any page regardless of the underlying programming platform, be it classic ASP, ASP.NET, Java Server Pages, PHP or plain HTML. ASP.NET AJAX: Partial Rendering By definition, the programming model for Ajax applications seems to be clear and unquestionable. You write code that captures client-side events, conduct an operation on the server via XMLHttpRequest, get the results, and update the user interface. All the client-side programming is done through JavaScript. Ajax applications require a change of paradigm and some imagination. When it comes to rewriting web applications for Ajax, nearly all aspects of the web application need to be redesigned, reconsidered, re-factored and often rewritten (and…ran out of words starting with re). But there is an easier way……In ASP.NET AJAX, it is called partial rendering. ASP.NET partial rendering is centered around a container control --- the UpdatePanel control. This control is used to surround portions of existing pages, or portions of new pages developed with the usual programming model of ASP.NET. A postback request that originates within any of these updatable regions is captured by the UpdatePanel control and resolved asynchronously using XMLHttpRequest. In this way, fresh HTML is downloaded for the selected region, bypassing the browser and reducing page flickering. Partial rendering is offered natively in ASP.NET 3.5 and works with older versions of ASP.NET through a separate download. LVSOnline - Where Learning is Fun! 6 of 17 Author: Frank Stepanski
  • 7. Partial rendering is build on top of the Microsoft ASP.NET AJAX infrastructure that includes a few other server controls as well as a general-purpose JavaScript library (both discussed later in this lesson). Motivation for Partial Rendering Partial rendering is an interesting compromise between a pure Ajax approach and the existing ASP.NET codebase. You don’t need to change anything in your server-side code. A postback always occurs, and the page life cycle is entirely preserved. The only difference between a partial rendering postback (a.k.a. async postback) and a classic postback is the involvement of the browser. The browser does it all in a classic postback model; the browser is bypassed in an async posback and doesn’t directly manage the request from start to finish. The impact of partial rendering on existing code is close to zero. All that you need to learn is how to use a small set of new server controls. No new application architecture is required, and no code re-factoring needs to be done. At the same time, by maintaining the classic ASP.NET application model, partial rendering doesn’t deliver you the full power of Ajax (discussed later). Installation of ASP.NET AJAX with Visual Studio With Visual Studio (and Visual Web Developer) 2008, ASP.NET AJAX is part of the IDE as well as being baked into the .NET Framework 3.5. This means that to use ASP.NET AJAX, you don’t need to install anything if you are working with ASP.NET 3.5. ASP.NET AJAX on the Server: AJAX Controls Visual Studio (and Visual Web Developer) 2008 includes a number of AJAX-based controls that you can use in your web applications: LVSOnline - Where Learning is Fun! 7 of 17 Author: Frank Stepanski
  • 8. ScriptManager The ScriptManager control is used to manage the generated client-side JavaScript AJAX code on your ASP.NET web pages. It is required for any page that uses ASP.NET AJAX, and only one can exist per page. ScriptManagerProxy Because only one ScriptManager control can exist in your page hierarchy (master page, inherited page, and so forth), you might want to define it in an ASP.NET master page to ensure that every page gets this functionality. If you do this, you must use the ScriptManagerProxy class in any page that inherits from the master page so that you can refer back to the original ScriptManager control. The ScriptManagerProxy will give you a locally defined object in your page, but will get all of its functionality from the referenced ScriptManager control. Timer The Timer control enables you to perform a synchronous or asynchronous postback at a defined interval. This is not a typical ASP.NET postback, but rather the XmlHttpRequest object that is generated in client-side script that is issuing a postback without refreshing the page. You can use the Timer control to perform periodic updates to your page with no user interaction. UpdatePanel The UpdatePanel control allows you to define a specific region on your page that can be updated asynchronously. UpdatePanel controls are one of the key controls of ASP.NET AJAX. They are used with the ScriptManager to enable partial-page rendering in your pages. UpdateProgress The UpdateProgress control enables you to provide visual feedback to your users while an asynchronous process is running. This control is important because it allows you to give your users visual cues that something is happening in the background while they are using your system. LVSOnline - Where Learning is Fun! 8 of 17 Author: Frank Stepanski
  • 9. Note: All these controls will be discussed in this class. ASP.NET AJAX on the Client: The Script Library No Ajax capability would ever be possible without a client-side engine right in the page. With today’s browsers, a similar engine can be written only in JavaScript. To do any serious programming on the client side of a web application, therefore, you need a rich, cross-browser extension to the core JavaScript language and the standard DOM. Enter the Microsoft JavaScript client library. The Microsoft JavaScript client library is a set of JavaScript files that, all together, power up the language with object-oriented features while hiding differences in the various browsers’ implementation of JavaScript and in the DOM implementations. The library also offers a stub for the XMLHttpRequest object and facilities for handling events. The script files forming the library are: • MicrosoftAjax.js - Core part of the library. It contains object-oriented extensions and capabilities for tracing and debugging. • MicrosoftAjaxWebForms.js – Contains script functions to support ASP.NET partial rendering. • MicrosoftAjaxTimer.js – Contains client-side programming interface of the Timer server control. The library is self-contained in the sense that it has no dependencies other than on the JavaScript language and standard interfaces of the DOM. The client libraries don’t expose much in the way of features (no pre-built features you can drop into your pages); rather they establish a basic foundation that you can use to LVSOnline - Where Learning is Fun! 9 of 17 Author: Frank Stepanski
  • 10. develop ASP.NET AJAX pages. This foundation extends the JavaScript language to fill in a few of its gaps and provides some basic infrastructure. Server-Side Ajax versus Client-Side Ajax Microsoft has a complicated relationship with Ajax. On the one hand, the company wants to provide its existing ASP.NET developers with an easy way to implement Ajax functionality without having to learn JavaScript. On the other hand, Microsoft recognizes that the future is on the client. Therefore, it wants to provide web developers the tools they need to build pure client-side Ajax applications. For these reasons, Microsoft has both a server-side Ajax framework and a client-side Ajax framework. If you want to retrofit an existing ASP.NET application to take advantage of Ajax, you can take advantage of Microsoft’s server-side Ajax framework. To take advantage of the server-side framework, you don’t need to write a single line of JavaScript code. You can continue to build ASP.NET pages with server-side controls in the standard way. The advantage of the server-side framework is that it provides existing ASP.NET developers with a painless method of doing Ajax. The disadvantage of the server-side framework is that it doesn’t escape all the problems associated with a server-side framework. You still have to run back to the server whenever you perform any client-side action. The Microsoft client-side Ajax framework embraces the client side. When building applications with the Microsoft client-side Ajax framework, you must build the application by using JavaScript. The advantage of building applications with the client-side framework is that you can build very rich and responsive web applications. You can build web applications with the same rich interactivity as a desktop application. Debugging Ajax Applications LVSOnline - Where Learning is Fun! 10 of 17 Author: Frank Stepanski
  • 11. Debugging Ajax applications presents challenges not present in a normal server-side application. If an Ajax call fails, you won’t necessarily know. You need a way of monitoring the Ajax calls that happen between the browser and server. The first tool is called Fiddler. You can download this tool (for free) at Fiddler enables you to view HTTP requests and responses, including Ajax calls. Fiddler works by installing itself as a proxy between your web browser and the rest of the universe. You can use Fiddler with Internet Explorer, Mozilla Firefox, Opera, Safari, and just about any other browser. When Fiddler launches, every browser request and response is recorded in the Fiddler Web Sessions pane. You can click a request and then click the Session Inspector tab to see the full request and response (Figure 2). Note: If you are using Microsoft Vista, you may need to disable IPv6 support. In Fiddler, select the menu option Tools, Fiddler Options, and uncheck the Enable IPv6 check box. The other critical Ajax debugging tool is Firebug, which is a free Firefox extension. Firebug, like Fiddler, enables you to monitor Ajax calls, but it enables you to do much more. After you install Firebug, you enable it by selecting the menu option Tools, Firebug and un-checking Disable Firebug. After Firebug is enabled, you can click the green check box at the bottom right of the Firefox browser to open Firebug. You can use Firebug to monitor Ajax requests and responses (among many other things). If you click the Net tab and the XHR tab, then every Ajax call will appear in the Firebug window (Figure 3). You can click a particular Ajax request to see the full request and response interaction between browser and server. LVSOnline - Where Learning is Fun! 11 of 17 Author: Frank Stepanski
  • 12. Figure 2 – Using Fiddler to veiew HTTP requests Figure 3 – Using Firebug to view Ajax calls LVSOnline - Where Learning is Fun! 12 of 17 Author: Frank Stepanski
  • 13. ASP.NET AJAX on the Server: The ScriptManager The ScriptManager is the brains of the server-side ASP.NET AJAX model. It’s a web control that doesn’t have any visual appearance on the page. However, it performs a key task --- it renders the links to the ASP.NET AJAX JavaScript libraries. To add the ScriptManager to a page (only one allowed per page), you can drag it from the AJAX Extensions tab of the Toolbox (Figure 3). Here is how the ScriptManager is declared in the .aspx file: <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> At design time, the ScriptManager appears as a blank gray box. But when you request a page that uses the ScriptManager you won’t see anything, because the ScriptManager doesn’t generate any HTML tags. Instead, it adds the links to the ASP.NET AJAX JavaScript libraries. It does this by inserting a script block that looks something like this: <script src="/WebSite/WebResource.axd?d=BwLm69XN8BJ … " type="text/javascript"></script> This script block doesn’t contain any code. Instead, it uses the src attribute to pull the JavaScript code out of a separate file. This long URL points to a ScriptResource.axd. ScriptResource.axd isn’t an actual file, it’s a resource that tells ASP.NET to find a JavaScript library file that’s embedded in one of the compiled >NET 3.5 assemblies. The long query string argument at the end of the URL tells the ScriptResource.axd extension which file to send to the browser. Figure 3 – ScriptManager is in AJAX Extensions in ToolBox LVSOnline - Where Learning is Fun! 13 of 17 Author: Frank Stepanski
  • 14. ASP.NET AJAX on the Server: The UpdatePanel The basic idea is that you divide your web page into one or more distinct regions, each of which is wrapped inside an invisible UpdatePanel. When an event occurs in a control that’s located inside an UpdatePanel, and this event would normally trigger a full-page postback, the UpdatePanel intercepts and performs an asynchronous callback instead. Here’s an example of how it happens: 1. The user clicks a button inside an UpdatePanel 2. The UpdatePanel intercepts the client-side click. Now, ASP.NET AJAX performs a callback to the server instead of a full-page postback. 3. On the server, your normal page life cycle executes, with all the usual events. Finally, the page is rendered to HTML and returned to the browser. 4. ASP.NET AJAX receives the full HTML and updates every UpdatePanel on the page by replacing its current HTML with the new content. A Simple updatePanel Test The following example uses a simple page that includes two ingredients: an animated GIF image, and a box that shows the current time and includes a Refresh button. Building this page is easy. First you add a ScriptManager control to the page. The ScriptManaer needs to appear before the UpdatePanel, because the rendered page must have the JavaScript block in place before the UpdatePanel can use it. So, it’s a good idea to always place the ScriptManager at the top of the page. Next, at the UpdatePanel and then the rest of the page content inside. As soon as there are elements inside the UpdatePanel the <ContentTemplate> will appear: <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Image ID="Image1" runat="server" ImageUrl="~/lava_lamp.gif" /> <br/></br/> <asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label> LVSOnline - Where Learning is Fun! 14 of 17 Author: Frank Stepanski
  • 15. <br/></br/> <asp:Button ID="Button1" runat="server" Text="Refresh Time" /> </ContentTemplate> </asp:UpdatePanel> Then, add the code to put the time in Label in Page_Load event: protected void Page_Load(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToLongTimeString(); } Very simple, right? ASP.NET AJAX isn’t too hard. ☺ Now of course you can intermingle using the UpdatePanel with certain parts of your web page. This example shows you the difference between using an UpdatePanel and not using it. Notice how it doesn’t matter whether you put the code in the Page_Load or the Event of the control. Though, personally, it is best if you put it in the Event of the control. http://www.aspdotnet- Additional Resources: Definition of Ajax by Jesse James Garrett: ASP.NET AJAX RoadMap: Understanding Partial Page Updates: LVSOnline - Where Learning is Fun! 15 of 17 Author: Frank Stepanski
  • 16. Assignment for Lesson 1 1. Read over this lesson and understand what ASP.NET AJAX is all about. 2. Install Firebug and Fiddler. 3. Take this existing example (or a web page you already have done): http://www.aspdotnet- And add a ScriptManager and UpdatePanel to it. Also add a 2-3 second pause when the login button is clicked. The code to add a pause is: System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); This pause will simulate a normal database request on a web site. My version: http://www.aspdotnet- Note: If you have a web host that supports ASP.NET AJAX (free Brinkster account does not), you may have to upload a new web.config. Just create a new web site and use the AJAX controls we have just discussed and the web.config will have the necessary updates to it. 4. Post on the class discussion board that your Lesson 1 is ready with a direct link to your page, such as: (or .zip) I will respond with a review on the class discussion board. LVSOnline - Where Learning is Fun! 16 of 17 Author: Frank Stepanski
  • 17. Copyright 2009 © Frank Stepanski Used with Permission: LVS Online Classes / LVS Associates Lessons, files and content of these classes cannot be reproduced and/or published without the express written consent of the author. Use of this site implies agreement with the Terms of Use LVSOnline - Where Learning is Fun! 17 of 17 Author: Frank Stepanski