Published: 13 Feb 2008
By: Alessandro Gallo

Get up to speed with ASP.NET AJAX by building a simple Virtual Earth mashup.


With ASP.NET AJAX, we can add AJAX functionality to ASP.NET pages. We can rely on a robust JavaScript library to perform tasks such as making asynchronous method calls and refreshing a portion of HTML without reloading the whole page. On the server side, comes a framework that leverages the power of the ASP.NET technology and lets you create Ajax-enabled server controls.

In this series, you will take a leap around the main features offered by ASP.NET AJAX. To make things less boring, you will put ASP.NET AJAX at work by creating a simple mapping mashup. A mashup is an application that relies on external services (web services) in order to retrieve the data it needs. Then, it typically uses AJAX techniques to manipulate and visualize such data. Since web mapping has been one of the preferred fields for mashups - especially in their early days - we will create a simple mapping application that utilizes the Virtual Earth API.

Loading a Virtual Earth map

The Virtual Earth API resides in a JavaScript file that must be loaded in the web page that is going to display a map. The latest version of the API - v6 at the time of this writing - can be downloaded by referencing the following URL:

Once the API is loaded, you create a map by instantiating an object of type VEMap. The constructor takes a string with the ID of a HTML element - a div, usually - that will display the map. This is shown in the following listing, which reports the code for an ASP.NET page that hosts a Virtual Earth map. If you browse the page, you'll see that a map is effectively displayed on screen.

Listing 1: Loading a Virtual Earth map in an ASP.NET page

The head tag of the HTML in the previous listing contains two script elements. The first one references the latest version of the Virtual Earth API. The second script tag holds the JavaScript code that loads the map. This code lives inside a function called loadMap, which is invoked as soon as the load event of the body element is fired. You can verify this by looking at the onload attribute of the body tag.

Inside loadMap, the VEMap constructor takes a string with the ID of the div that is going to display the map, and returns a map object that is saved in the global theMap variable. Before calling the LoadMap method of the map object, you assign a function to its onLoadMap property. This function (a callback) is executed as soon as the map is loaded, and it's an ideal place to interact with the Virtual Earth API.

If you want to set a different zoom level, you can do so by calling the SetZoomLevel method and passing an integer between 1 and 19. Let's say that you want to center the map at a different point: First, you create a VELatLong object with the latitude and longitude coordinates. Then, you pass this object to the SetCenter method of the map, like so:

So far, everything works great and you are able to leverage all the functionality provided by the Virtual Earth API in your ASP.NET page.

In fact, this little web application suffers a series of (typical) symptoms that may compromise its overall design and cause problems related to performance and maintainability. Let's see what's wrong with it.

ASP.NET AJAX to the rescue

The code shown in listing 1 works, though it's not the kind of code you would write when leveraging a server-side technology like ASP.NET.

Despite being a dynamic page, it looks fairly static. We find hard-coded URLs, the head tag is filled with JavaScript code and almost everything is declared as static HTML. On the other hand, ASP.NET provides techniques to generate portions of the page's HTML on the server side. Dynamic generation of the markup becomes fundamental when we want to encapsulate some functionality and we need to configure it based on the particular environment in which the website runs. What if we want to target a different version of the API? Do we have to manually synchronize the URL in every page? And what happens if we want to change how the client map object is initialized based on user preferences?

The way the client side code is written betrays some bad habits. Attaching event handlers like we are doing with the onload attribute leads to a mix of markup and code that can be the root cause of multiple problems. For example, how can we detach that event handler? Unfortunately, Internet Explorer 6 and other browsers are known to leak memory when event handlers aren't properly detached before the page is unloaded. This, in turn, can lead to huge performance drops as the application becomes slow and less responsive.

Another problem with the JavaScript code in listing 1 is the use of global variables. Since object-oriented languages exist, we have been taught that global variables violate the fundamental principles of Information Hiding and Modularity: They prevent state partitioning and therefore the code that uses a global variable is visible and thus accessible to all the application code. Furthermore, the code that uses the variable is almost always located too far from where the variable is declared. Experience has shown that using global variables is risky, and yet they're found everywhere in the client side code of web applications.

Again: Are we sure that our web application runs as expected in all the modern browsers? As we know, writing cross-browser applications (that is, web applications that provide the same user experience in multiple browsers) has always been a hard job. Sometimes, dealing with all the incompatibilities in different versions of JavaScript turns into a real pain. Nowadays, cross-browser compatibility has become a requirement for web applications since the advent of the Web 2.0 paradigm.

If you agree that we've found enough problems given the small size of the code in listing 1, you have to think to what happens when we start adding pages and writing more markup and client side code. It's very likely that those that could have been called issues now have become nasty bugs. As soon as we fix them, we may be forced to repeat a same, long sequence of modifications on and on. Rest assured that the nature of the Web (that lets you mix data and code) can really make things worse.

What's stated in the previous paragraphs encourages particular care in how mashups - and, in general, dynamic pages - are structured. For this reason, a good approach is using a server side technology combined with a client side library that leverages AJAX techniques. You'll end up rewriting the code in listing 1 into that shown in listing 2.

Listing 2: The code in listing 1 rewritten with ASP.NET AJAX

The code in listing 2 leverages the power of ASP.NET server controls. Furthermore, one of the features of ASP.NET AJAX is the ability to automatically initialize a web page for AJAX. In this series, you'll get up to speed with the main tools that ASP.NET AJAX provides in order to create mashups and rich web applications.

The final step in this introductive article is configuring a new website for ASP.NET AJAX.

Configuring an ASP.NET website for AJAX

If you are targeting the .NET Framework 3.5, everything you have to do is creating a new ASP.NET Website from within Visual Studio 2008.

If you are targeting the .NET Framework 2.0, the procedure is slightly more complex because ASP.NET AJAX lives in a separate assembly. One solution is to use the website template added to Visual Studio 2005 by the ASP.NET AJAX installer. If you want to proceed manually, the first thing to do is editing the Web.config file in order to add all the configuration settings required by ASP.NET AJAX. The quickest way, if you are creating a new website, is to replace the existing file with the Web.config file located in the ASP.NET AJAX installation directory. If you open this file, you'll notice that the assemblies section references the System.Web.Extensions assembly:

The System.Web.Extensions assembly contains all the ASP.NET AJAX features. It should be installed in the GAC (the Global Assembly Cache, a place in the local filesystem where shared assemblies are stored). This is done automatically by the ASP.NET AJAX installer. If you need further assistance, be sure to check the Reference section at the end of this article.

At this point, we've got a working ASP.NET AJAX website. The first step to enable AJAX in a web page is to declare a ScriptManager control, like so:

The ScriptManager control is the brains of an ASP.NET AJAX page. It takes care of initializing the AJAX runtime and provides several features, such as the ability to render script references and to automatically inject the code needed to configure client side JavaScript object.

The next part of this series will demonstrate this by showing how to create ASP.NET AJAX-enabled server controls.


In this introductive article, we have explained how mashups and rich web applications can benefit from the use of ASP.NET AJAX. We have compared a classical, pure-HTML approach to writing a Virtual Earth mashup against a more server oriented strategy that takes advantage of ASP.NET AJAX. As a first step toward the next part of this series, we have configured a fresh website for use with ASP.NET AJAX.


<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Alessandro Gallo

Alessandro "Garbin" Gallo is a Microsoft MVP in the Visual ASP/ASP.NET category and a .NET developer/consultant. He is a contributor for the Ajax Control Toolkit project, owned by Microsoft. Alessandro won the Grand Prize at the "Mash-it-up with ASP.NET AJAX" contest held by Micr...

This author has published 23 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category

Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
This is my custom article

You might also be interested in the following related blog posts

Telerik Introduces Free Web Testing Framework for ASP.NET AJAX and Silverlight read more
New ASP.NET 3-8x accelerator is in public beta read more
My Latest Book – Professional ASP.NET 3.5 AJAX read more
Session Slides and Samples from Microsoft ASP.NET Connections read more
AJAX >> Using AJAX to load a usercontrol that has refers to a custom css file read more
ASP.NET Memory Issues read more
EOAST - Evolution of a software thingy - Part 1 read more
Building Virtual Earth applications just keeps getting easier read more
How to setup a new AjaxEngine web project read more
Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Performing Client Actions in Response to Partial Page Postbacks read more


Subject Author Date
placeholder Converted cs file to vb file Alan Stirling 5/12/2009 11:31 AM
RE: Converted cs file to vb file Alan Stirling 5/13/2009 5:33 AM
placeholder Kool Kazi Manzur Rashid 2/14/2008 9:50 AM
Great article Bryan Reynolds 6/2/2008 5:39 PM
placeholder I'm getting an error when I try to run this Olice Certain 1/9/2009 2:07 PM
RE: I'm getting an error when I try to run this Olice Certain 1/9/2009 5:06 PM

Please login to rate or to leave a comment.