Calling WCF and ASMX Services with AjaxMethodCallback

You can also call WCF and ASMX Ajax style Web Services by using the AjaxMethodCallback control. The control provides the following:

  • Automatic script loading for jquery.js and ww.jquery.js
  • JSON encoding and decoding including dates
  • Proxy generation so you get methods that match server methods

Effectively you get most of the functionality you also see with ASP.NET AJAX for service callbacks without the Microsoft client libraries requirement.

Create a WCF Service

Let's assume we have a WCF service that's set up like this.

Service Markup:

<%@ ServiceHost Language="C#" Debug="true" 
                Service="Westwind.WebToolkit.Ajax.WcfServiceCallbacks" 
                CodeBehind="WcfServiceCallbacks.svc.cs" 
                Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"                
%>

Using the WebScriptServiceHostFactory is the quickest way to set up a Web Service for ASP.NET AJAX compatibility. This service takes JSON messages as input and output and use POST data for input messages.

Service Implementation:

    [ServiceContract]
    public class WcfServiceCallbacks 
    {
        [OperationContract]
        public string HelloWorld(string name)
        {
            return "Hello World from Wcf, " + name + ". Time is: " + DateTime.Now.ToString();
        }

        [OperationContract]
        public int AddNumbers(int num1, int num2)
        {
            return num1 + num2;
        }

    }

Hit the service page and make sure the service responds with the default service page.

Connect the WCF Service to AjaxMethodCallback

Now you're ready to hook up the client. Start by dropping an AjaxMethodCallback control onto the page and pointing it at the WCF or ASMX service you'd like to call:

<ww:AjaxMethodCallback ID="Proxy" runat="server" 
                       Timeout="4000" 
                       ServiceType="Wcf" 
                       ServerUrl="WcfServiceCallbacks.svc" />

Next in the code behind specify the .NET type of the implementing service class:

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            <<b>>this.Proxy.ClientProxyTargetType = typeof(WcfServiceCallbacks);<</b>>
        }

This ensures that proxy methods that map the service contract are generated.

Call the Web Service from JavaScript

At this point you're ready to make the service call:

function SayHello() {
    // Id is mangled by ASP.NET so use serverVars created with ScriptVariables
    // component which generates a client object with simple client Id names
    var name = $("#" + serverVars.txtNameId).val();

    Proxy.HelloWorld(name,
        // function called with the method result
        function(result) {
            $("#divHelloMessage")
                .text(result)
                .stop()
                .fadeIn("slow");

            setTimeout(function() { $("#divHelloMessage").fadeOut("slow"); }, 8000);
        },
        // error handler
        onError);
}

Proxy in this case is a generated JavaScript class that has the same name as the ID you specified in the AjaxMethodCallback control. Every service method on the service is exposed through this proxy with each of the parameters as input parameters followed by Callback and Error handlers that are called on success and failed requests. The Callback receives the result value from the server as a value (value, array or object).

Here's the code for the AddNumbers callback:

function AddNumbers() {
    
    // pick up inputs and turn into numeric values that hte server 
    // AddNumbers expects
    var num1 = $("#" + serverVars.txtNum1Id).val() * 1;
    var num2 = $("#" + serverVars.txtNum2Id).val() * 1;
        
    // Use the generated Proxy to call the server
    Proxy.AddNumbers(num1, num2,
        function(result) {
            $("#" + serverVars.lblAddResultId).text(result);
        }, onError);
}

Notice that here the values passed are numeric. The server expects a numeric value and that's what the client has to send. The result is in result as a number as well so no conversion is required. Any complex return values are returned as well.

Benefits of using this Control

  • Fully self contained - scripts loaded from resources
  • Easy Proxy access just as you get with ASP.NET AJAX libraries
  • No requirement for the MS AJAX client libraries (uses jquery.js and ww.jquery.js)
  • Proper date parsing in all types
  • Same Proxy Synax for calling West Wind Handlers, ASMX and WCF Services

Our preference the technology to use for calling services are (in this order):

  • Callbacks to West Wind CallbackHandlers
  • Callbacks to Page handlers
  • ASMX Callbacks
  • WCF Callbacks

Using the West Wind handler/page callbacks provides a little more flexibility as all resources and related dependencies are included. You also get automatic serialization of DataTable, DataSet and DataRows, ISO style date formatting for optimal JSON parsing on the client and support for anonymous types and dictionaries.


© West Wind Technologies, 1996-2016 • Updated: 04/10/13
Comment or report problem with topic