Published: 05 Mar 2008
By: Alessandro Gallo
Download Sample Code

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

Introduction

In the second part of this series, you saw how to create client Controls and Extenders using the Microsoft Ajax Library and the ASP.NET AJAX server framework. Now, you will learn how to make asynchronous calls to the server in order to process data without reloading a web page.

The Web uses a stateless protocol (HTTP) to exchange data. As a consequence, a user interacts with a web page through multiple request-response transactions. Typically, an action performed by the user (such as submitting a form, or clicking a hyperlink) results in the browser requesting a web page from the server. Therefore, the state of a web application is reloaded at each request. At the same time, the user interface is rendered from scratch.

AJAX (Asynchronous JavaScript and XML) is born when a technique was invented to make the request-response interaction happen in the background - hence the term Asynchronous - without reloading the state of the web application and its whole user interface. This is possible with a JavaScript object called XmlHttpRequest, which was introduced in Internet Explorer 5 and then gradually embedded in all the modern browsers.

In this article, you are going to leverage the ASP.NET AJAX framework in order to make asynchronous calls in a straightforward and transparent way, without directly touching the XmlHttpRequest infrastructure.

Asynchronous calls to Web Services

The Microsoft Ajax Library provides a set of JavaScript objects that let you perform asynchronous calls at a higher level than interacting directly with the XmlHttpRequest object.

The first thing you are going to do is invoke a Web Service asynchronously in order to retrieve some data to display in the Virtual Earth map that you created in the previous parts of this series. Specifically, the data will be displayed as pushpins on the map.

One of the interesting things that you can do with this technique is exchange data by serializing and deserializing server types. This means that, if you declare a Pushpin class on the server side and return an instance through a Web Service, you will be able to access a Pushpin object with the same data in JavaScript, on the client side.

To see how it's done, let's start by creating a Pushpin class on the server side, in the App_Code folder of the website. This is shown in the following listing.

Listing 1: The Pushpin class on the server side

As you can see, this is just a plain old .NET class that holds the relevant data for a Virtual Earth pushpin. More interesting is the declaration of the Web Service that you are going to use to exchange data asynchronously.

Listing 2: The Web Service that will be called asynchronously

Actually, it requires a little effort to perform a basic configuration of a Web Service for ASP.NET AJAX. This is the step-by-step procedure, which you can verify against the previous code snippet:

  • Declare the Web Service class and decorate the web methods with the WebMethod attribute, as usual.
  • Decorate the class with the ScriptService attribute. This attribute is defined in the System.Web.Script.Services namespace.

The final thing to do is let the ScriptManager control know that we are going to call a Web Service from the client side. This is done by adding a Services section inside the ScriptManager tag. This section holds a ServiceReference tag, which provides the path to the Web Service.

Listing 3: Referencing the Web Service through the ScriptManager

At this point, the Web Service is ready to be called from the client side. Let's demonstrate how it's done by adding the following script block inside the form tag of the web page:

The above code snippet reveals how simple the syntax used to invoke the Web Service from the client side is. In fact, we can invoke a web method by calling a method exposed by a JavaScript object with the same name of the Web Service.

Note: If the Web Service is declared inside a namespace called Samples, then you have to use its fully qualified name - that is, Samples.PushpinService.

Behind the Scenes

What happens is that ASP.NET AJAX generates a proxy of the Web Service. The proxy is just a JavaScript object with the same name of the Web Service. Its methods have the same names as the web methods. By calling the proxy, you are actually making an asynchronous call to the Web Service. Finally, the result of the call is returned back to the server, and can be processed in a callback method. This is the function that we passed to the PushpinService.GetPushpins method of the proxy. The other function is a callback that gets invoked in case something goes wrong.

If you want to take a look at the proxy's generated code, you can either

  • Append /PushpinService.asmx/js to the URL of the ASP.NET page and browse it. A call is made to an ASP.NET Handler - called ScriptResourceHandler - that returns the code for the proxy, which is displayed on screen.
  • Set the InlineScript attribute of the ServiceReference tag to true. This instructs the ScriptManager to render the code inline in the page's HTML.

Another interesting thing happens whenever we invoke a web method. If the web method returns instances of types defined on the server side, these instances are serialized and turned into JavaScript objects. This means that we can access Pushpin objects on the client side. Furthermore, we can also create instances of Pushpin objects in JavaScript and pass them to web methods. As result, these client instances are turned into server side instances.

Note: The serialization/deserialization of instances of server types is relative to the data held by the objects and exposed through properties. Methods are not involved in the serialization/deserialization process. Furthermore, there's no built-in support for serialization/deserialization of some complex types such as DataSets and DataTables.

Getting Pushpins from the server

After that quick peek at how Web Services calls work in ASP.NET AJAX, let's modify the Mashup.VirtualEarth client Control in order to display a group of pushpins retrieved through the Web Service you created previously.

For this purpose, you have to add some methods that take the Pushpin instances on the client side and turn them into Virtual Earth pushpins. These methods are shown in the following listing.

The previous code works in a simple manner. The client calls the set_data method, passing an array of objects that contain data for the pushpins to display. The properties of these objects are the same exposed by the Pushpin class on the server side. It follows that you have to modify the JavaScript code in the script block (that we used to test the Web Service call) in order to call the set_data method, passing the Pushpin[] array returned by the web method. This is demonstrated in the following code.

Listing 4: Retrieving pushpins from the server side

The $find method used in the previous code is rather interesting. It lets you get a reference to a client component instantiated using the $create method. You can use $find to access the client VirtualEarth Control, since it was instantiated with a call to $create by the VirtualEarth Extender.

The $find approach allows accessing JavaScript objects without declaring any global variables at all.

Figure 1 shows the mashup up and running.

Figure 1: The Virtual Earth mashup

Summary

The essence of AJAX is the possibility to make requests to the web server asynchronously, without being forced to reload the whole page each time the state of the page changes. The Microsoft Ajax Library provides a framework that takes care of doing most of the job required to interact with the XMLHttpRequest object. As a result, making asynchronous calls to the server and processing the results is easy and straightforward.

In this article we explained how to call ASP.NET Web Services from the client side. You learned how to configure a Web Service for ASP.NET AJAX and how to invoke the client proxy in order to make the asynchronous call.

In the next part of this series, we will dive deeper in the networking layer of 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 asp.net 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...
Test120Jan
This is my custom article

You might also be interested in the following related blog posts


New ASP.NET 3-8x accelerator is in public beta read more
AJAX >> Using AJAX to load a usercontrol that has refers to a custom css file read more
Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Performing Client Actions in Response to Partial Page Postbacks read more
Impressive author lineup over at DotNetSlackers read more
April 11th Links: ASP.NET, ASP.NET AJAX, ASP.NET MVC, Visual Studio, Silverlight read more
Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Using the UpdatePanel read more
Partial Rendering Misses AJAX Architectural Points read more
Tools of a SharePoint consultant read more
Difference between our two AJAX books read more
New Best Practice: Ajaxifying UserControls read more
Top
 
 
 

Discussion


Subject Author Date
placeholder Issue with adding eventhandlers to the map Michael Norman 6/25/2009 11:28 PM
RE: Issue with adding eventhandlers to the map Michael Norman 6/25/2009 11:32 PM
placeholder Error: 'null' is null or not an object Mike Frizzell 6/27/2009 2:17 PM
RE: Error: 'null' is null or not an object Mike Frizzell 6/27/2009 3:01 PM
placeholder RE: Error: 'null' is null or not an object Sonu Kapoor 6/27/2009 2:41 PM
RE: RE: Error: 'null' is null or not an object Mike Frizzell 6/27/2009 3:02 PM
placeholder RE: RE: Error: 'null' is null or not an object Mike Frizzell 6/27/2009 3:09 PM
RE: RE: RE: Error: 'null' is null or not an object Mike Frizzell 6/27/2009 3:33 PM
placeholder RE: RE: RE: RE: Error: 'null' is null or not an object Sonu Kapoor 6/27/2009 3:41 PM
RE: Error: 'null' is null or not an object Mike Frizzell 6/27/2009 3:04 PM
placeholder How to add markers using data retrieved from a database query Julio M 11/10/2009 2:31 PM
problem Rav W 3/12/2008 6:56 PM
placeholder RE: problem Alessandro Gallo 3/15/2008 11:53 AM
RE: RE: problem Sonu Kapoor 3/15/2008 6:35 PM
placeholder RE: RE: RE: problem Alessandro Gallo 3/15/2008 6:42 PM
Problem with initial Latitude / Longitude Walt Cygan 4/9/2008 9:29 AM
placeholder RE: Problem with initial Latitude / Longitude Alessandro Gallo 5/2/2008 5:52 AM
RE: Problem with initial Latitude / Longitude Walt Cygan 4/9/2008 9:59 AM
placeholder RE: Problem with initial Latitude / Longitude Lynn Demarest 3/28/2009 10:17 PM
3D Broken? James Swansburg 4/11/2008 11:49 PM
placeholder RE: 3D Broken? Gary Nicol 4/16/2008 4:36 AM
Great Article Michael Liscio 4/16/2008 1:46 PM
placeholder How can I do the coding for MouseUp, MouseDown events in the code Anshu Bhatia 4/22/2008 2:26 PM
RE: How can I do the coding for MouseUp, MouseDown events in the code Alessandro Gallo 5/2/2008 5:56 AM

Please login to rate or to leave a comment.