Consuming Web Services With ASP.NET AJAX
(
Jun 03 2007 - 06:01:58 PM by
Timothy Khouri) - [
print article]
One of the most powerful features of ASP.NET AJAX is often times one of the most overlooked uses - consuming web services. Many ASP.NET developers are beginning to implement AJAX into their site by the use of the drop-in-place controls such as the UpdatePanel, ModalPopup and Timer. This article will focus on some of the deeper things of ASP.NET AJAX.
Developers sometimes lose site of the purpose of a tool, and instead become enamored with how 'shiny' it is. This problem becomes epidemic when well-meaning folks want to sell their product, and so they pump up the 'shiny factor' to a point where the original meaning (and the semantic meaning) is dead and gone. One of the great reasons and purposes of AJAX is to connect programming interfaces with your thin-client web application. It really helps convert "web pages" to true "web applications". This transformation will be even more apparent and beautiful with WCF.
The Need for AJAX
Web applications were really born with the introduction of ASP.NET rebuilding the 'state' of your "web form" from the view state, providing real object oriented programming and so much more. The problem still remained though with the web being so disconnected. In windows programming, you could click a button and it would fire code only belonging to that button, but in the web, you have to rebuild the page. This means all your code in PreInit, PageLoad, PreRender etc. has to fire over and over again. This needed to be fixed, and it has been thanks to ASP.NET AJAX.
This following example will demonstrate a simple 'real world' need that has been really brought together using AJAX. We will see how clean the code becomes and discuss some of the clear benefits of this approach.
The Scenario - A Zip Code Lookup
The scenario that we are going to work on is the need for a product website to inform the user of the nearest dealer to them based on the zip code that they enter. While it is true that you can just post back to the server, recreate the entire page, add the desired content to the page and maybe scroll their browser down to see the new results, that is doing way more than it needs to. On top of it all, our 'Zip Code Lookup' functionality will need to be publicly exposed to some other affiliate websites, so the functionality needs to be publicly accessible.
The solution is very simple. We are going to build a Web Service that does the zip code lookup for us. This will allow us to use it in our own web application, and it will also expose the functionality to the public. Let see how easy it is to consume that web service with ASP.NET AJAX.
The Web Service Code
First let's take a quick look at the Web Service code so that we can get an understanding of what we will be working with. This code is very simple, and I intentionally am just returning a hard coded result for the purpose of this demo. Here is the code:
using System;
using System.Web.Services;
using System.Web.Script.Services;
[ScriptService]
public class VendorLocator : WebService
{
[WebMethod, ScriptMethod]
public SearchResult GetNearestDealer()
{
return new SearchResult(10, "Bob's Widget Store", "(555) 567-8901");
}
}
public class SearchResult
{
public SearchResult(int distance, string name, string phoneNumber)
{
this.distance = distance;
this.name = name;
this.phoneNumber = phoneNumber;
}
private int distance;
public int Distance
{
get { return this.distance; }
set { this.distance = value; }
}
private string name;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
private string phoneNumber;
public string PhoneNumber
{
get { return this.phoneNumber; }
set { this.phoneNumber = value; }
}
}
There are a few things to notice here. First of all, you'll notice that we had to add a few attributes to our class and method so that ASP.NET will know that we plan on exposing these abilities to ASP.NET AJAX. This does not hurt the application in any way and will not change the way anyone else uses the web service, but rather it adds functionality. The two attributes that we needed was the "ScriptService" attribute on the class and the "ScriptMethod" attribute on the method. Very simple so far.
Another thing to note is that we made our own custom class to hold our search data. ASP.NET AJAX will automatically JSON (JavaScript Object Notation) serialize all of the public properties (in this case "Distance", "Name" and "PhoneNumber") and pass them as a parameter back to JavaScript.
The ASP.NET Code
Now let's lookat our ASP.NET code for our web application that is going to consume this Web Service:
<form runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server" />
<h1>
Demo Product Lookup</h1>
<p>
Enter your zip code below to find the closest product vendor.</p>
<fieldset>
<label>
Zip Code<input type="text" ID="ZipCode" /></label>
<button onclick="findVendor();">
Search
</button>
</fieldset>
<dl id="dealerResults" style="display: none;">
<dt>Distance:</dt>
<dd id="distance" />
<dt>Name:</dt>
<dd id="name" />
<dt>Phone:</dt>
<dd id="phoneNumber" />
</dl>
</form>
With a little bit of styling, the above code looks like this:
The JavaScript Code
Our button's "onclick" property is set to call the function 'findVendor'. That JavaScript code will look like this:
function findVendor() {
var zipCode = $get("ZipCode").value;
VendorLocator.GetNearestDealer(function(result) {
$get("distance").innerHTML = result.Distance;
$get("name").innerHTML = result.Name;
$get("phoneNumber").innerHTML = result.PhoneNumber;
$get("dealerResults").style.display = "";
});
}
When we enter in our zip code and press the search button we get the following results:
Concluding Remarks
ASP.NET AJAX does all of the hard work for us, and beautifully returns our "SearchResult" object which we built in C#! What they have done is truly amazing. The "result" object that comes back from our function call will have all properties populated and accessible in our JavaScript code. The communication to the server, the creation of the client-side function, the JSON serialization - it's all handled by ASP.NET AJAX. So get excited about the web again, start to think of web applications as being 'connected', and for goodness' sake, mash it up with ASP.NET AJAX.
(Edit: 5/2/2008 - I've finally taken the time to redo this demo and upload the source code. Here it is: SingingEels_AjaxWebServices.zip)