Freigeben über


Walkthrough: Creating and Using AJAX-Enabled Web Service

Visual Studio 2008 and Microsoft Visual Web Developer Express let you create ASP.NET custom Web services (.asmx files) that you can access from client script. In this walkthrough, you will create an AJAX-enabled Web service and call its methods by using client script.

When you create ASP.NET Web services and expose them to client script, ASP.NET automatically creates JavaScript proxy classes for the Web services. You can call a Web service method by calling the corresponding method of the JavaScript proxy class.

This walkthrough shows:

  • How to create an AJAX-enabled Web service in Visual Studio 2008 or Microsoft Visual Web Developer Express.

Prerequisites

In order to complete this walkthrough, you need:

  • Visual Studio 2008 or Microsoft Visual Web Developer Express.

  • Microsoft Internet Information Services (IIS) installed locally on your computer. For more information, see Installing IIS 7.0 on Windows Vista on the IIS Web site.

Creating an AJAX-enabled Web Service

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

Note

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.

    Note

    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 (https://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]:="http://mycompany.org/"), _
        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 
            'InitializeComponent(); 
    
            <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
    
    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    
    namespace Samples.Aspnet
    {
        [WebService(Namespace="http://mycompany.org")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        // The following attribute allows the service to 
        // be called from script using ASP.NET AJAX.
        [System.Web.Script.Services.ScriptService]
        public class HelloWorld : System.Web.Services.WebService
        {
    
            public HelloWorld()
            {
    
                //Uncomment the following line if using designed components 
                //InitializeComponent(); 
            }
    
            [WebMethod]
            public string Greetings()
            {
                string serverTime =
                    String.Format("Current date and time: {0}.", DateTime.Now);
                string greetings = "Hello World! <br/>" + serverTime;
                return greetings;
            }
    
        }
    }
    

    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" %>
    
    <%@ WebService Language="C#" CodeBehind="~/App_Code/HelloWorld.cs" 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: https://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 (https://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.
        helloWorldProxy.set_defaultSucceededCallback(SucceededCallback);
        helloWorldProxy.set_defaultFailedCallback(FailedCallback);
    }
    
    
    // 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: " + 
                error.get_message();
        }
    }
    
    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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
        <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 }
            </style>
    
            <title>Using AJAX Enabled ASP.NET Service</title>
    
        </head>
    
        <body>
            <form id="Form1" runat="server">
                <asp:ScriptManager runat="server" ID="scriptManager">
                    <Services>
                        <asp:ServiceReference path="~/HelloWorld.asmx" />
                    </Services>
                    <Scripts>
                        <asp:ScriptReference Path="~/HelloWorld.js" />
                    </Scripts>
                </asp:ScriptManager>
                <div>
                    <h3>Using AJAX Enabled ASP.NET Service</h3>
    
                    <table>
                        <tr align="left">
                            <td>Click to call the Hello World service:</td>
                            <td>
                                <button id="Button1" 
                                    onclick="OnClickGreetings(); return false;">Greetings</button>
                            </td>
                        </tr>
                    </table>
    
                </div>
            </form>
    
            <hr/>
    
            <div>
                <span id="Results"></span>
            </div>   
    
        </body>
    
    </html>
    
    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
        <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 }
            </style>
    
            <title>Using AJAX Enabled ASP.NET Service</title>
    
        </head>
    
        <body>
            <form id="Form1" runat="server">
                <asp:ScriptManager runat="server" ID="scriptManager">
                    <Services>
                        <asp:ServiceReference path="~/HelloWorld.asmx" />
                    </Services>
                    <Scripts>
                        <asp:ScriptReference Path="~/HelloWorld.js" />
                    </Scripts>
                </asp:ScriptManager>
                <div>
                    <h3>Using AJAX Enabled ASP.NET Service</h3>
    
                    <table>
                        <tr align="left">
                            <td>Click to call the Hello World service:</td>
                            <td>
                                <button id="Button1" 
                                    onclick="OnClickGreetings(); return false;">Greetings</button>
                            </td>
                        </tr>
                    </table>
    
                </div>
            </form>
    
            <hr/>
    
            <div>
                <span id="Results"></span>
            </div>   
    
        </body>
    
    </html>
    

    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:

    http://<localhost>/HelloWorldService/Default.aspx

  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.

Next Steps

This walkthrough has illustrated the basic principles of creating a Web service and then calling it in a Web page from client script. You might want to experiment with additional, more complex Web service features. Suggestions for additional exploration include the following:

See Also

Concepts

Exposing Web Services to Client Script

Calling Web Services from Client Script

Using Web Services in ASP.NET AJAX