Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Different methods to call Web Services from AJAX

2.28/5 (8 votes)
25 Oct 2007CPOL2 min read 1   1.1K  
Different methods of calling Web Services from AJAX.

Introduction

This article briefly explains the various ways in which a Web Service method can be called using AJAX.

Background

Lots of articles are out there explaining how AJAX and Web Services interact together while trying to solve various problems. I have put together just the interaction ways. In short, here are the different ways to call a Web Service from AJAX.

Using the code

The code below demonstrates the different methods starting with the traditional approach of No AJAX as the base.

The code snippets are arranged as:

  • Web Service
  • ASPX and
  • C# code-behind

Before AJAX

This section can just be glanced over to see how a Web Service method used to be called on postback from a server control like a button.

No JavaScript - Postback required to populate Label1

C#
//WebService

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World " + DateTime.Now.ToString();
        //Or call the method on the real webservice traditional way
    }
}

Client ASPX:

ASP.NET
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" 
  OnClick="Button1_Click" Text="Button" />
</form>
</body>

Client code-behind:

C#
public partial class _Default : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        MyService myService = new MyService();
        Label1.Text = myService.HelloWorld();
    }
}

Using AJAX

Method 1

This section explains how a Web Service can be called by modifying the ScriptManager.

Using AJAX - Postback not required to populate Label1

  1. Add the ScriptService() attribute to the Service class.
  2. Add the <Services> tag to the ScriptManager.
  3. Convert the server controls "Label" and "Button" to HTML controls.
  4. Call the Web Service method from JavaScript which is actually a proxy call.
  5. Remove the Click handler from the code-behind.
C#
//WebService

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class MyService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World " + DateTime.Now.ToString();
        //Or call the method on the real webservice traditional way
    }
}

Client ASPX:

ASP.NET
<script language="javascript" >
function onClick(){
    MyAjaxApplication.MyWebService.HelloWorld(OnComplete, 
                      OnTimeOut, OnError);
    return true;
}
function OnComplete(args) {
    document.getElementById('Label1').innerHTML = args;
}
function OnTimeOut(args) {
    alert("Service call timed out.");
}

function OnError(args) {
    alert("Error calling service method.");
}</script><body>

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="MyService.asmx" />
</Services>
</asp:ScriptManager>
<label id="Label1" style="width: 318px"></label>
<input id="Button1" type="button" 
  value="button" onclick="return onClick();" />
</form></body>

Client code-behind:

C#
public partial class _Default : System.Web.UI.Page
{
    //empty
}

Method 2

This section explains how a Web Service can be called from a CascadingDropDown Toolkit control with or without the intermediate page method.

Using AJAX page method and the CascadingDropDown control from the Toolkit- Postback not required to populate the combo

  1. Add a new method to the service to return the CascadingDropDownValue[] collection. This will act as the data source for the dropdownlists.
  2. Remove the <Services> tag from the ScriptManager.
  3. Remove EnablePageMethods from the ScriptManager.
  4. Remove the label and the textbox controls.
  5. Add two DropDownList server controls and two CascadingDropDowns (from the Toolkit) to the client page.
  6. Set the service name and method of the first CascadingDropDown.
  7. Set the page method only for the second Cascadingdropdown.
C#
//WebService

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class MyWebService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World " + DateTime.Now.ToString();
    }
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public CascadingDropDownNameValue[] GetHelloList(
            string knownCategoryValues, string category)
    {
        string result = HelloWorld();
        List<CascadingDropDownNameValue> values = 
              new List<CascadingDropDownNameValue>();
        values.Add(new CascadingDropDownNameValue("Hello", result)); 
        return values.ToArray();
    }

Client ASPX:

ASP.NET
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
From Direct Service call
<asp:DropDownList ID="DropDownList1" 
  runat="server" Width="285px" />
<br />
Through Page Method
<asp:DropDownList ID="DropDownList2" 
  runat="server" Width="285px" />
<br />
<cc1:CascadingDropDown ID="CascadingDropDown1" 
  runat="server" Category="Hello"
  TargetControlID="DropDownList1" 
  ServicePath="MyService.asmx" 
  ServiceMethod="GetHelloList">
</cc1:CascadingDropDown>

Client code-behind:

C#
public partial class _Default : System.Web.UI.Page
{
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] 
      GetHelloListPageMethod(string knownCategoryValues, string category){
    return new MyWebService().GetHelloList(knownCategoryValues, category);
}
}
//Note: If this PageMethod is used, the servicepath attribute 
//on the Cascadingdropdown in aspx should be removed

Points of interest

Hope this clears out a lot of confusion especially for people trying to work out how to access Web Services. I am open to comments.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)