Search Wiki:

WCF Complex Type AJAX Service Sample

This sample demonstrates how to use Windows Communication Foundation (WCF) to create an ASP.NET Asynchronous JavaScript and XML (AJAX) service that creates instances of complex types and sends them between service and client as JavaScript Object Notation (JSON). You can access an AJAX service by using JavaScript code from a Web browser client.

Download WCF Complex Type AJAX Service
Watch - WCF Complex Type AJAX Service Sample

AJAX support in WCF is optimized for use with ASP.NET AJAX through the ScriptManager control. For an example of using WCF with ASP.NET AJAX, see the AJAX Samples .

The service in the following sample is a WCF service with no AJAX-specific code. Because the WebGetAttribute attribute is not applied, the default HTTP verb ("POST") is used. The service has one operation, DoMath, which returns a complex type named MathResult. The complex type is a standard data contract type, which also contains no AJAX-specific code.

public class MathResult
    public double Difference;
    public double Product;
    public double Quotient;
    public double Sum;

Create an AJAX endpoint on the service by using the WebScriptServiceHostFactory , just as in the Basic AJAX Service sample.

<%@ ServiceHost 

The client Web page ComplexTypeClientPage.aspx contains ASP.NET and JavaScript code to invoke the service when the user clicks the Perform calculation button on the page. The code to invoke the service constructs a JSON body and sends it using HTTP POST, similar to the AJAX Service Using HTTP POST sample.

After the service call succeeds, you can access the individual data members (sum, difference, product and quotient) on the resulting JavaScript object.

// This function is called when the result from the service call is received
function onSuccess(mathResult) {
    document.getElementById("sum").value = mathResult.Sum;
    document.getElementById("difference").value = mathResult.Difference;
    document.getElementById("product").value = mathResult.Product;
    document.getElementById("quotient").value = mathResult.Quotient;

Try It

  1. Press F5 to debug
  2. Enter two numbers
  3. Click perform calculation
Last edited Dec 11 2010 at 12:06 AM  by RonJacobs, version 7
Page view tracker