Three Ways to Consume Web Services with AJAX
page 6 of 9
by Xianzhong Zhu
Feedback
Average Rating: 
Views (Total / Last 10 Days): 65936/ 67

Access Web Services the Microsoft way—through ASP.NET AJAX 1.0 Framework

Now, let us look into the Microsoft way of consuming Web Services with AJAX.

About ASP.NET AJAX 1.0

ASP.NET AJAX (formerly referred to as "Atlas") was an add-on to ASP.NET 2.0, with the goal of aiding developers in creating more interactive AJAX-enabled Web applications. The framework includes two distinct yet not mutually exclusive API's: client and server, which enable the developers to accomplish AJAX functionalities using direct client-side programming, traditional server-side programming, or any combination of both. Figure 4 shows the client architecture of the asynchronous communication layer of this framework.

Figure 4: Client-side architecture of ASP.NET AJAX framework

The client architecture contains two main groups: the communication group and the support group. The communication group contains client script that performs Web services communication between the client and the server. Note that Web request handling is intrinsically an asynchronous process. The communication group is based on the browser’s XMLHTTP object and on executor objects that dispatch browser requests to the Web service. In Microsoft ASP.NET AJAX, the asynchronous communication layer generates client-script proxy classes automatically. You can then use the JavaScript proxy objects to make asynchronous requests to the server from client script. There are two possible approaches to making a Web service request:

·         Calling Web services by using the HTTP POST verb. In this way, there is not a size limitation. Therefore, you can use a POST request when the size of the data exceeds the intrinsic size limitation for a GET request. The client serializes the request into JSON format and sends it as POST data to the server. The server deserializes the JSON data into .NET types and makes the actual Web service call. During the response, the server serializes the return values and passes them back to the client, which deserializes them into JavaScript objects for processing.

·         Calling Web services by using the HTTP GET verb. This resembles the functionality of a POST request, with the following differences:

          1. The client uses a query string to send the parameters to the server.

          2. A GET request can call only a Web service method that is configured by using the [ScriptMethod(UseHttpGet = true)] attribute.

          3. Data size is limited to the URL length allowed by the browser.

Author's Notes: ASP.NET AJAX's web services layer, by default, does not allow web methods to be invoked via the HTTP GET verb in order to prevent it from being susceptible to various types of JSON hijacking attacks. So, to make an ASP.NET AJAX web-method callable via HTTP GET-access, a developer must explicitly attribute each method using ASP.NET's ScriptMethod attribute (and set the UseHttpGet property to true).

Since our main attention is focusing on how to call web services with AJAX, we only give you the framework's server architecture of the asynchronous communication layer.

Figure 5: Server-side architecture of ASP.NET AJAX framework

Enough of theory debate—let us get into some code!

Sample 2

1. Create an ASP.NET AJAX-Enabled sample Web Site

Again, launch Visual Studio 2005 and then select menu item "File | New Website…" to create a new website using the template named "ASP.NET AJAX-Enabled Web Site " and name the project WebServiceTest (again select Visual C# as the built-in language).

Next, with a little modification, page Default.aspx finally looks like Figure 6.

Figure 6: The design-time sample web page for Sample 2

Notice that as soon as the wizard ends there is automatically added a ScriptManager server control. This server control acts as the center of whole ASP.NET AJAX 1.0 framework, taking charge of management and scheduling of various JavaScript libraries used by the client-side runtime. Here, for the purpose of testing to call Web Services from inside client-side JavaScript, we drop a HTML Input Button onto the page, as well as three HTML Input Text controls.

2. Create a Web Service

Next, we will write a web service to be accessed via the browser JavaScript. Here, only for illustration, we let the service calculate the sum of two integers.

Right click the project and choose "Add new item" and create a new Web Service named SumService.asmx. Next, we are going to open file SumService.cs and create our own WebMethodGetSum.

According to the framework, we must put the attribute ScriptService before the Web Service so as for JavaScript to call it. Listing 6 gives the crucial code snippet.

Listing 6

using System.Web.Services.Protocols;
using System.Web.Script.Services;
 
namespace SumServiceSpace
{
  [ScriptService]
  public class SumService: System.Web.Services.WebService
  {
    [WebMethod]
    //[ScriptMethod(UseHttpGet = true)]
    public int GetSum(int a, int b)
    {
      return (a + b);
    }
  }
 
}

Here, WebMethod GetSum is to calculate the sum of two given integers.

Author's Notes: The Microsoft AJAX Library enables client script and the Web service to exchange complex types. In this sample, we only consider the simple one. For details, please see the online tutorial (ajax.asp.net).

3. Consume the Web Service

Now we get to the really interesting thing. Please switch to the Design View of page Default.aspx and click control ScriptManager1. Next, click the "…" on the right side of attribute Services in the Property window and enter into the dialog box, operating in the sequence as Figure 7 shows.

Figure 7: declaratively programming the control ScriptManager from the Property dialog box

OK, the last related source code looks like the code below.

Listing 7

<asp:ScriptManager ID="ScriptManager1" runat="server" >
  <Services>
   <asp:ServiceReference Path="SumService.asmx" />
  </Services>
</asp:ScriptManager>

Here, we have created an instance of ServiceReference with attribute Path pointing to the service file SumService.asmx in the declarative way.

Finally, we are to code how to call the web service proxy with the values of the two TextBox controls passed to it. Double click the Get the sum via a Web Service button in Figure 5 above and add the following into the event handler.

Listing 8

function btnSum_onclick()
{
  SumServiceSpace.SumService.set_defaultSucceededCallback(OnSuccess);
 
  SumServiceSpace.SumService.GetSum(eval(form1.TextBoxA.value), eval
    (form1.TextBoxB.value), OnSuccess());
 
}
 
function OnSuccess(result)
{
  $get("TextBoxSum").value = result;
}

Here, the most important thing to be noticed is that calling a Web service method from script is asynchronous. As the framework says, to get a return value or to determine when the request has returned, you must provide a callback function. The callback function is invoked when the request has finished successfully. The function exposes the return value. So, OnSuccess here corresponds to the callback functionall the manipulation with the values post back from the web service's methods is done herein. Another important thing to notice is method GetSum is passed into three arguments (in fact there' is still one omitted here) while the one defined in the Web Service merely takes two! Why? This extra parameter represents the name of the callback function as a pointer to the function called when the service invocation succeeds (the other omitted one corresponds to the function called when the service invocation fails or overtime). Apparently, this calling approach hides the asynchronous feature of AJAX (have we associated this with the mechanism and usage of the great many callbacks with Win32 API?).

Still, one thing to be emphasized is whether the call is successful or not; web methods defined in the Web Service should return a value contained in the parameter result of the callback. In this scenario, for each successful request/response the parameter result contains the sum of two given integers. By the way, $get("TextBoxSum") corresponds to the commonly used document.getElementById("TextBoxSum") in DOM programming, which is simplified by the ASP.NET Ajax framework.

4. Running the sample and Troubleshooting

Without any trouble, press F5 and you will see the runtime screenshot like Figure 8.

Figure 8: The runtime screenshot of Sample 2

Subtle readers may notice that after you have entered two integers in the TextBoxes above and press the Get the sum via a Web Service button, there will appear a strange string'Undefined' before you get the correct result6912. Regrettably, I have not found the why for now, so sincerely welcome anyone who can help me with the trouble.


View Entire Article

User Comments

Title: Sr. Web Developer   
Name: Nelson Xu
Date: 2008-09-04 11:20:30 AM
Comment:
Hi Xianzhong,
I reall enjoy your article and code sample.
The reason that "Undefined" appears is because you have () for OnSuccess when you call Web service.

SumServiceSpace.SumService.GetSum(
eval(form1.TextBoxA.value),
eval(form1.TextBoxB.value),
OnSuccess());

Message will go away if you remove () after OnSuccess.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 8:30:08 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search