Click here to Skip to main content
Click here to Skip to main content

Different methods to call Web Services from AJAX

, 25 Oct 2007
Rate this:
Please Sign up or sign in to vote.
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

//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:

<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:

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.
//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:

<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:

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.
//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:

<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:

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)

About the Author

Gyan Jadal
Architect
United States United States
Software Architect

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 76899783-Dec-11 23:22 
QuestionHow to get the value of the dropdownlist and update the database Pinmemberxrf_mail31-Oct-10 23:59 
GeneralMy vote of 1 PinmemberAntony M Kancidrowski6-Feb-09 4:46 
GeneralQuery regarding one line of onClick() Pinmemberrobvon23-Dec-08 12:41 
Generalajax control: dynamic populate PinmemberNikoTanghe20-Nov-07 1:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 25 Oct 2007
Article Copyright 2007 by Gyan Jadal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid