SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (35)
  • LINQ (4)
  • Security (2)
  • Silverlight (2)
  • SQL (7)
  • Standards (5)
  • WCF (2)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box
ASP.NET Hosting with MS SQL 2008 – Click Here!

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 we, 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()
   {
       // We are intentionally returning a hard coded result for this example.

       return new SearchResult(10, "Bob's Widget Store", "(555) 567-8901");
   }
}

// This is our "SearchResult" class which will automatically be JSON serialized

// by ASP.NET AJAX and passed into JavaScript as a parameter.

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:

Zip code search example for AJAX web services demo

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) {
       // Assign the Distance

       $get("distance").innerHTML = result.Distance;

       // Assign the Name

       $get("name").innerHTML = result.Name;

       // Assign the Phone Number

       $get("phoneNumber").innerHTML = result.PhoneNumber;

       // Make the dealer results visible

       $get("dealerResults").style.display = "";
   });
}

When we enter in our zip code and press the search button we get the following results:

Zip code search example for AJAX web services demo with search 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.

Update: May 02 2008

I've finally taken the time to redo this demo and upload the source code. Here it is: SingingEels_AjaxWebServices.zip

Update: Jul 29 2008

There is a bug mentioned in a comment below in FireFox with this sample... I've fixed it, here's the fixed link: SingingEels_AjaxWebServices_2.zip

  • Jul 14 2007 - 12:28:57 AM liming

    Great working example!

    I'm really digging your style. Finally someone is creating a "real-world" scenario by combining both server side with the MS ajax client sided script.

    It will be great if you could write an article on using MS client sided ajax with say Ext JS library.

  • Jul 14 2007 - 10:01:17 AM Luciano Terra

    Could you share the source code solution for this post?

  • Jul 14 2007 - 04:52:51 PM Timothy Khouri

    Honestly, I think I've deleted the source code. I'll see if I can find it in my archives, and if I can't, I'll just redo it and post it.

  • Jul 16 2007 - 07:11:22 PM Sojan

    Timothy,

    I'd agree, its nice article, but it leaves me with some questions. So, if a website is putting out this web service, (in your example you talked about making it available to other "vendor dealers" in the area), so how would they go about including this in their site, and could a web service like this be consumed / used by one of the dealers if they were still running a classic ASP site or would its functionality only be available to ASP.NET and ASP.NET Ajax site?

  • Jul 16 2007 - 07:39:07 PM Timothy Khouri

    Well, if you are familiar with creating web services in ASP.NET, then you know that they can be consumed just like any other web service. However, I'm pretty sure that you can only call web services in ASP.NET AJAX that belong to your application.

    So, you can't call an ASP.NET AJAX web service hosted on www.SingingEels.com from www.LostInTangent.com.

    I did delete the source code for the above article (as I only created it for the article). But I will re-create it (or something simialar) tonight and post it at the end of this article.

  • Jul 16 2007 - 07:41:57 PM Timothy Khouri

    After reading my above comment, I don't think I clearly answered your question about other people using the web service... They can utilize the service just like normal... the only difference is that we added the "WebMethod" attribute to it so that we can ALSO use it in AJAX (on the same site).

  • Jul 29 2007 - 11:15:58 PM purplebz

    Thanks for the nice article.

    But Im not sure where to put the javascript code is it in <head> tag? Im getting javascript error that VendorLocator is undefined. Please help.

  • Jul 31 2007 - 06:17:48 AM Timothy Khouri

    The JavaScript can go anywhere in the page (in the <head> tag is fine). The "VendorLocator" is a C# method inside of my custom web service. Because I deleted the source code for this demo a while ago, I'm going to just recreate it and post it at the end of the article.

  • Mar 30 2008 - 12:45:12 PM mia892

    Is there a link to download the code or is the above complete?

  • May 02 2008 - 02:55:07 PM Timothy Khouri

    I've finally taken the time to add the source code (I had to rewrite it)... the link is up above at the end of the article.

  • May 22 2008 - 10:36:23 AM ajitgoel

    I second liming comment. It will be great if you could write an article on using MS client sided ajax with say Ext JS library.

  • Jul 29 2008 - 04:35:53 PM tony

    Timothy,

    Your sample code doesn't work in Firefox.

  • Jul 29 2008 - 08:01:07 PM Timothy Khouri

    Hey Tony,

    I just re-downloaded the solution, and it works in FireFox, but firefox does a post back afterword! So... if you add "return false;" (<button onclick="findVendor(); return false;">) to the button click, it's 'fixed'.

    Thanks for finding that bug!

    -Timothy

  • Jul 30 2008 - 07:15:54 PM naiplehb

    Great example!!Readers of this article would know how great ASP.Net Ajax was. Thanks to you and to Microsoft!! lol!

You must be logged in to add comments. If you have not already done so, you can create an account here. If you already are a member, you first need to login before you can comment.

Developer / Architect / Author

People to Follow

Experts in the categories related to this article.

  • Jonathan Carter

Related Blogs

These are the most recent blog posts related to this article.

  • A Change to the MVC "ActionSelectionAttribute"?
  • How to Handle "Side Content" in ASP.NET MVC
  • LINQ to SQL - Am I Hitting The Database?
  • ASP.NET MVC - Issue with CSS Class Name on ActionLinks
  • Site Updates, Bug Fixes and Syndication in .NET 3.5

Related Ads

SingingEels.com as of Nov 21 2008 - 04:40:32 PM - (0.1718706)