Creating and Using AJAX-Enabled Web Service

This section describes how to create an AJAX-enabled Web service.


You must use an IIS Web site for this walkthrough.

To create an AJAX-enabled Web service

  1. Open Visual Studio 2008. or Microsoft Visual Web Developer Express.

  2. On the File menu, click New Web Site.

    The New Web Site dialog box appears.

  3. Under Visual Studio installed templates, click ASP.NET Web Site.

  4. Click Browse.

  5. Click Local IIS.

  6. Click Default Web Site.

  7. In the upper-right corner, click the Create New Web Application icon.

    Visual Studio creates a new IIS Web application.

  8. Specify the name HelloWorldService.

    The name of the Web site that you are creating is not important.

  9. Click Open.

    The New Web Site dialog box is displayed, with the name of the new Web site in the rightmost Location list. The location includes the protocol (http://) and location (localhost). This indicates that you are working with a local IIS Web site.

  10. In the Language list, select the programming language that you prefer to work in.

  11. Click OK.

Writing the Custom Web Service

This section describes how to write an AJAX-enabled Web service that provides a method that returns the string "Hello World" and the current server time.

To write the custom Web service

  1. In Solution Explorer, right-click the Web site name (http://localhost/HelloWorldService), and then click Add New Item.

  2. Under Visual Studio installed templates, click Web Service, and then in the Name box, type HelloWorld.asmx.

  3. Make sure that the Place code in separate file check box is selected, and then click Add.

    Visual Studio 2008 creates a new Web service that consists of two files. The HelloWorld.asmx file is the file that can be invoked to call Web service methods. It points to the Web service code. The code itself is in a class file (HelloWorld.vb or HelloWorld.cs, depending on the programming language) in the App_Code folder. The code file contains a template for a Web service.

  4. Delete the existing code in the class and replace it with the following code:

    Imports System
    Imports System.Web
    Imports System.Collections
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    Namespace Samples.Aspnet
        <WebService([Namespace]:=""), _
        WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1), _
        System.Web.Script.Services.ScriptService()> _
        Public Class HelloWorld
            Inherits System.Web.Services.WebService
            Public Sub New()
            End Sub 'New
            'Uncomment the following line if using designed components 
            <WebMethod()> _
            Public Function Greetings() As String
                Dim serverTime As String = _
                    String.Format("Current date and time: {0}.", DateTime.Now)
                Dim greet As String = "Hello World. <br/>" + serverTime
                Return greet
            End Function 'Greetings
        End Class 'HelloWorld
    End Namespace

    Notice that the function names are preceded with the WebMethodAttribute attribute as part of the function declaration. In addition, the HelloWorld class is qualified with the ScriptServiceAttribute attribute.

    These attributes enable the Web service to be called from script in AJAX-enabled ASP.NET Web pages.

  5. Save the file and close it.

  6. Open the HelloWorld.asmx file and add the following directive:

    <%@ WebService Language="VB" CodeBehind="~/App_Code/HelloWorld.vb" Class="Samples.Aspnet.HelloWorld" %>
  7. Save the file and close it.

Now you can test the Web service in your browser. This test does not use script to call the Web service methods. This is only to verify that the Web service is working correctly.

To test the Web service

  1. Open the browser and enter the following URL: http://localhost/HelloWorldService/HelloWorld.asmx

    The Web service is invoked and a page appears in the browser that shows the methods that are exposed by the Web service.

  2. Click Greetings. A page appears with the Invoke button.

  3. Click the Invoke button to call the method and see the returned value in XML format.

  4. Close the browser.

You have finished creating the AJAX-enabled Web service.

Using the Web Service

The next step is to call the Web service from client script.

To call the Web service from client script

  1. In Solution Explorer, right-click the Web site name (http://localhost/HelloWorldService), and then click Add New Item.

  2. Under Visual Studio installed templates, click JScript File, and then in the Name box, type HelloWorld.js.

  3. Click OK.

  4. Add the following code to the script file:

    var helloWorldProxy;
    // Initializes global and proxy default variables.
    function pageLoad()
        // Instantiate the service proxy.
        helloWorldProxy = new Samples.Aspnet.HelloWorld();
        // Set the default call back functions.
    // Processes the button click and calls
    // the service Greetings method.  
    function OnClickGreetings()
        var greetings = helloWorldProxy.Greetings();
    // Callback function that
    // processes the service return value.
    function SucceededCallback(result)
        var RsltElem = document.getElementById("Results");
        RsltElem.innerHTML = result;
    // Callback function invoked when a call to 
    // the  service methods fails.
    function FailedCallback(error, userContext, methodName) 
        if(error !== null) 
            var RsltElem = document.getElementById("Results");
            RsltElem.innerHTML = "An error occurred: " + 
    if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

    This client script will be used by the Default.aspx page to call the HelloWorld service methods.

  5. In Visual Studio 2008, open the Default.aspx page.

  6. Delete the existing markup in the page and replace it with the following code:

    <%@ Page Language="VB" AutoEventWireup="false" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    <html xmlns="">
        <head id="Head1" runat="server">
            <style type="text/css">
                body {  font: 11pt Trebuchet MS;
                        color: #000000;
                        padding-top: 72px;
                        text-align: center }
                .text { font: 8pt Trebuchet MS }
            <title>Using AJAX Enabled ASP.NET Service</title>
            <form id="Form1" runat="server">
                <asp:ScriptManager runat="server" ID="scriptManager">
                        <asp:ServiceReference path="~/HelloWorld.asmx" />
                        <asp:ScriptReference Path="~/HelloWorld.js" />
                    <h3>Using AJAX Enabled ASP.NET Service</h3>
                        <tr align="left">
                            <td>Click to call the Hello World service:</td>
                                <button id="Button1" 
                                    onclick="OnClickGreetings(); return false;">Greetings</button>
                <span id="Results"></span>

    The page contains a ScriptManager control. The path attribute in the ServiceReference element of the Services section references the HelloWorld service that you built previously. The path attribute in the ServiceReference element of the Script section references the HelloWorld.js script.

  7. Open the browser and enter the following URL:


  8. In the displayed page, click the Greetings button.

    This generates a call to the Web service that returns a greeting message and the current server date and time.