Calling Web Services from Client Script

This topic explains how to use the AJAX functionality of ASP.NET to call a Web service from ECMAScript (JavaScript). To enable your application to call ASP.NET Web services by using client script, the server's Web service communication layer automatically generates JavaScript proxy classes. A proxy class is generated for each Web service that is referenced by an ServiceReference element in the ScriptManager control in the page.

The Web services can be in the form of .ASP.NET Web services (.asmx services), or Windows Communication Foundation (WCF) services (.svc services). If you have already created ASP.NET Web services (.asmx), you can modify them to enable script in your AJAX-enabled Web pages to call them. For more information, see Exposing Web Services to Client Script. If you have already created WCF services, you can add end-points to enable script in AJAX-enabled Web pages to access the services. For more information, see Exposing WCF Services to Client Script.

To call a method of the Web service, you call the corresponding method of the generated JavaScript proxy class. The proxy class in turn communicates with the Web service.

Calling a Web service method from script is asynchronous. To get a return value or to determine when the request has returned, you must provide a succeeded callback function. The callback function is invoked when the request has finished successfully, and it contains the return value (if any) from the Web method call. You can also provide a failed callback function to handle errors. Additionally, you can pass user context information to use in the callback functions.

The following example shows how to make the following types of Web service calls:

  • Calling a Web service that has no return value.

  • Calling a Web service that returns a value.

  • Calling a Web service method that takes parameters.

  • Calling a Web service method by using the HTTP GET verb.

  • Calling a Web service method that returns an XmlDocument object.

The first part of the example shows a Web page that makes service calls by using client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the Web page to call the Web service.


// This function calls the Web service method without 
// passing the callback function. 
function GetNoReturn()
{
    Samples.AspNet.WebService.GetServerTime();
    alert("This method does not return a value.");

}


// This function calls the Web service method and 
// passes the event callback function.  
function GetTime()
{
    Samples.AspNet.WebService.GetServerTime(
    SucceededCallback);

}


// This function calls the Web service method 
// passing simple type parameters and the 
// callback function  
function Add(a,  b)
{
    Samples.AspNet.WebService.Add(a, b, 
    SucceededCallback);
}

// This function calls the Web service method 
// that returns an XmlDocument type.  
function GetXmlDocument() 
{
    Samples.AspNet.WebService.GetXmlDocument(
        SucceededCallbackWithContext, FailedCallback,
        "XmlDocument")
}

// This function calls a Web service method that uses
// GET to make the Web request.
function MakeGetRequest() 
{

    Samples.AspNet.WebService.EchoStringAndDate(
        new Date("1/1/2007"), " Happy",
        SucceededCallback, 
        FailedCallback, "HappyNewYear");

}

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object, the user context, and the 
// calling method name as parameters.
function SucceededCallbackWithContext(result, userContext, methodName)
{
    var output;

    // Page element to display feedback.
    var RsltElem = document.getElementById("ResultId");

    var readResult;
    if (userContext == "XmlDocument")
	{
	
	    if (document.all) 
	        readResult = 
		        result.documentElement.firstChild.text;
		else
		    // Firefox
		   readResult =
		        result.documentElement.firstChild.textContent;
		
	     RsltElem.innerHTML = "XmlDocument content: " + readResult;
	}

}

// This is the callback function invoked if the Web service
// succeeded.
// It accepts the result object as a parameter.
function SucceededCallback(result, eventArgs)
{
    // Page element to display feedback.
    var RsltElem = document.getElementById("ResultId");
    RsltElem.innerHTML = result;
}


// This is the callback function invoked if the Web service
// failed.
// It accepts the error object as a parameter.
function FailedCallback(error)
{
    // Display the error.    
    var RsltElem = 
        document.getElementById("ResultId");
    RsltElem.innerHTML = 
    "Service Error: " + error.get_message();
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();



The next part of the example shows the Web service that is called by the page.

No code example is currently available or this language may not be supported.

In the previous examples, calls to Web service methods are made by using the proxy class. Information about the succeeded callback function, the failed callback function, and the user context is passed by using additional parameters in the call.

As an alternative, you can specify a succeeded callback function, a failed callback function, and user context as default properties for the class. Your script can then invoke the Web service methods of the proxy class without passing these values as parameters in the call. This simplifies the syntax of calling Web service methods.

The following example shows how to set default properties on the Web service proxy class, and then call a Web service method.

MyNameSpace.MyService.set_defaultSucceededCallback(SucceededCallback);
MyNameSpace.MyService.set_defaultFailedCallback(FailedCallback);
MyNameSpace.MyService.set_defaultUserContext("my context");
MyNameSpace.MyService.myServiceMethod(param1, param2);

Setting Callback Functions as Properties of Proxy Class Instances

You can also create instances of the generated proxy class. In that case, you can specify a succeeded callback function, a failed callback function, and user context as default properties for each instance. As with calling the generated proxy class, you can then use the proxy class instances to call Web service methods without passing these values as parameters in the call.

You typically create proxy-class instances when you want to make multiple calls to methods of the Web service and use different default property values for each instance. For example, you can specify different callback functions for each instance. By using different callback functions, you can process the returned data in different ways based on your application needs and on the nature of the returned data.

The following example shows how to create an instance of a proxy class, set its default properties, and call the related Web service method:

var myServiceProxy = new MyNameSpace.MyService();
myServiceProxy.set_defaultSucceededCallback(SuccededCallback);
myServiceProxy.set_defaultFailedCallback(FailedCallback);
MyNameSpce.MyService.set_defaultUserContext("my context");
myServiceProxy.myServiceMethod(param1, param2); 

For more information, see Generated Proxy Classes.

In order to catch errors, you must provide a failed callback function that accepts a single parameter. This parameter will contain the error object sent by the Web service.

The following example shows how to provide a failed callback function that is called if an error occurs during a Web service method call. The first part of the example shows a Web page that calls a Web service by using client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the page to call the Web service.


// This function can cause a divide by zero error.  
function Div(a, b)
{
    Samples.AspNet.WebService.Div(a, b, 
        SucceededCallback, FailedCallback);
}

// This is the failed callback function.
function FailedCallback(error)
{
    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();

    // Display the error.    
    var RsltElem = 
        document.getElementById("Results");
    RsltElem.innerHTML = 
        "Stack Trace: " +  stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout;
}

// This is the succeeded callback function.
function SucceededCallback(result)
{
    // Display the result.
    var RsltElem = document.getElementById("Results");
    RsltElem.innerHTML = result;
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();



The next part of the example shows the Web service that is called by the page.

No code example is currently available or this language may not be supported.

You can provide a single succeeded callback function that is invoked from multiple Web service method calls. In order for the function to distinguish between callers, you can pass user context to it, or you can test for the name of the calling method. The user context and the calling method name are both available in the callback function.

The following example shows how to call a single callback function from multiple Web service requests. The first part of the example shows a Web page that calls a Web service by using client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the Web page to call the Web service.

// This function calls a Web service method 
// passing simple type parameters and the user context.  
function AddWithContext(a,  b, userContext)
{
    Samples.AspNet.WebService.Add(a, b, 
    SucceededCallbackWithContext, FailedCallback, userContext, null);
}


// This function calls the Web service method 
// passing the method name.  
function AddWithMethod(a,  b)
{
    Samples.AspNet.WebService.Add(a, b, 
    SucceededCallbackWithContext, FailedCallback);
}

// This is the callback function called if the
// Web service succeeded. It accepts the result
// object, the user context, and the method name as
// parameters.
function SucceededCallbackWithContext(result, userContext, methodName)
{
    // It holds feedback message.
	var output = "";
	
	// Page element to display the feedback message.    
    var RsltElem = 
        document.getElementById("Results");

    if (userContext)
    {
        output += "The user context is : " + userContext + "<br/>";
        RsltElem.innerHTML =  output;
        return;
 	}

	if (methodName) 
  	  output += "The method name is : " + methodName + "<br/>";
  	  
  	RsltElem.innerHTML =  output;
 	
}

// This is the callback function called if the
// Web service failed. It accepts the error object
// as a parameter.
function FailedCallback(error)
{
    // Display the error.    
    var RsltElem = 
        document.getElementById("Results");
    RsltElem.innerHTML = 
        "Service Error: " + error.get_message();
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


The next part of the example shows the Web service that is called by the page.

No code example is currently available or this language may not be supported.

If the Web service method returns a complex type, the succeeded callback function receives a return value in the form of a JavaScript object that corresponds to the server type.

The following example shows a Web service method that returns a complex type. The first part of the example shows a Web page that calls a Web service by using client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the page to call the Web service.

// It gets the default color
// from the Web service.
function GetDefaultColor()  
{
    // Call the Web service method to get 
    // the default color.
    Samples.AspNet.HandleColor.GetDefaultColor(
        SucceededCallback);  

}

// This is the callback function that 
// processes the complex type returned  
// by the Web service.
function SucceededCallback(result)
{

    // Read the values returned by the
    // Web service.
    var message = result.message;
    var rgb = result.rgb;
    var timeStamp = result.timeStamp;

    // Transform the rgb array into a string.
    var serverColor = rgb[0]+ rgb[1] + rgb[2];

    // Display the result.
    var displayResult = 
        document.getElementById("ResultId");
    displayResult.style.color = "yellow";
    displayResult.style.fontWeight = "bold";
    if (document.all) 
        displayResult.innerText = message + " " + timeStamp;
	else
	   // Firefox
	   displayResult.textContent = message + " " + timeStamp;
    displayResult.style.backgroundColor = "#" + serverColor;

}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


The next part of the example shows the Web service that is called by the page.

No code example is currently available or this language may not be supported.

The following example shows how to call Web service methods that have parameters that correspond to complex types. Proxy classes for the types will be automatically generated. This enables client script to create instances of the type to pass as parameters to the method call.

The first part of the example shows a Web page that calls a Web service by using client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the Web page to call the Web service.

 // The Web service default color.
 var defaultRgb;

 // The page feedback display element.
 var displayResult;

// Gets the selection list colors and 
// the default color from the Web service.
function GetServerColors()  
{
  // Gets the default color.
    Samples.AspNet.HandleColor.GetDefaultColor(
        SucceededCallback, FailedCallback);  

    // Get selection list colors.
    Samples.AspNet.HandleColor.GetColorList(
        SucceededCallback, FailedCallback);


}

// This function passes the color selected
// by the user (client) to the Web service.
function OnChangeDefaultColor(comboObject)  
{
    // Create an instance 
    // of the server color object.
    var color = 
        new Samples.AspNet.ColorObject();

    // Get the user's selected color.
    var selectionIndex = 
        comboObject.selectedIndex;
    var selectedColor = 
        comboObject.options[selectionIndex].text;    

    // Get the related RGB color value.
    var selectionValue = 
        comboObject.value;
    // Transform it into an array.
    var colorArray = selectionValue.split(",");

    // Assign the new values to 
    // the server color object.
    color.message = "The new default color is " + selectedColor + ".";
    color.rgb = colorArray;

    // Call the Web service method to change the color.
    Samples.AspNet.HandleColor.ChangeDefaultColor(
        color, SucceededCallback, FailedCallback);  
}

// This is the callback function that processes 
// the complex type returned by the Web service.
function SucceededCallback(result, userContext, methodName)
{ 
    switch(methodName)
    {
        case ("GetColorList"):
        {
            // Get the select object.
            var selectObject = document.getElementById("ColorSelectID");
            var i = 0;

            // Iterate through the dictionary to populate 
            // the selection list.
            for(var item in result)
            {        
                var option = new Option(result[item], item);
                selectObject.options[i]=option;

                // Set the default selection.        
                if (item == defaultRgb)
                    selectObject.options[i].selected = true;
               i++;
            }
            break;
        }
        default:
        {
            // Get the server default color and its current time.
            // Read the values returned by the
            // Web service.
            var message = result.message;
            defaultRgb = result.rgb;

            var timeStamp = result.timeStamp;

            // Transform the rgb array into a string.
            var serverColor = defaultRgb[0]+ defaultRgb[1] + defaultRgb[2];

            // Display the result.
            displayResult.style.color = "yellow";
            displayResult.style.fontWeight = "bold";
            if (document.all) 
                displayResult.innerText = message + " " + timeStamp;
            else
               // Firefox
               displayResult.textContent = message + " " + timeStamp;

            displayResult.style.backgroundColor = "#" + serverColor;
            break;
        }
    }            
}

// Callback function invoked on failure 
// of the Web service methods.
function FailedCallback(error, userContext, methodName) 
{
    if(error !== null) 
    {
        displayResult.innerHTML = "An error occurred: " + 
            error.get_message();
    }
}

// Gets the Web service selection list colors 
// and the default color.
function pageLoad() 
{
    // Get page feedback display element.
    displayResult = 
        document.getElementById("ResultId");
    // Get the server's selection list colors and 
    // the default color.
    GetServerColors();
}


if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


The next part of the example shows the Web service that is called by the page.

<%@ WebService Language="C#" Class="Samples.AspNet.HandleColor" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;

namespace Samples.AspNet
{
    // Define the color object to
    // exchange with the client.
    public class ColorObject
    {
        public string message;
        public string[] rgb; 
        public string timeStamp;

        public ColorObject()
        {
            this.message = "The default color is Red.";
            this.rgb = new string[] { "FF", "00", "00" };
            this.timeStamp = DateTime.Now.ToString();
        }
    }

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [GenerateScriptType(typeof(ColorObject))]
    [ScriptService]
    public class HandleColor : 
        System.Web.Services.WebService
    {


        [WebMethod]
        public ColorObject GetDefaultColor()
        {
            // Instantiate the default color object.
            ColorObject co = new ColorObject();
            return co;         
        }


        [WebMethod]
        public ColorObject ChangeDefaultColor(ColorObject color)
        {
            // Instantiate the default color object.
            ColorObject co = new ColorObject();
            // Assign the passed values.
            co.message = color.message;
            co.rgb = color.rgb;
            // Set time stamp.
            co.timeStamp = DateTime.Now.ToString();
            return co;
        }

        [WebMethod]

        public Dictionary<String,String> GetColorList()
        {
            //Instatiate the dictionary object.
            Dictionary<String, String> result = new Dictionary<string, string>();

            //Add the color items.
            result.Add("00,00,FF", "Blue");
            result.Add("FF,00,00", "Red");
            result.Add("00,FF,00", "Green");
            result.Add("00,00,00", "Black");

            return result;
        }          
    }

}


Passing Parameters Typed as Generics or Arrays

A Web service method might support parameters or a return value that are typed as generics or as arrays of lists of type T. In that case, ASP.NET automatically generates proxy classes for the type T for use with client script.

However, if a generic type takes more than one type argument, such as Dictionary<string, <T>>, ASP.NET does not automatically generate proxy classes for the types. For ASP.NET to generate a proxy class for the type T, the Web service class that uses the type must be qualified with the GenerateScriptTypeAttribute attribute for the type T.

The following example shows how to call a Web service method from client script when the parameters are typed as generics or arrays. The first part of the example shows a Web page that calls a Web service by using client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the Web page to call the Web service.


// The page feedback display element.
var displayResult;

// This function intializes the global variables and
// assigns default values to the generated proxy.
function pageLoad() 
{
    // Get page feedback display element.
    displayResult = 
        document.getElementById("ResultId");

    // Assign default values to the generated proxy.
    Samples.AspNet.TestService.set_defaultUserContext("Default context");
    Samples.AspNet.TestService.set_defaultSucceededCallback(SucceededCallback);
    Samples.AspNet.TestService.set_defaultFailedCallback(FailedCallback);
 }

 // Get a generic List.
 function GenericList() 
 {	   
    Samples.AspNet.TestService.GetGenericList(); 
 }

 // Get a generic Dictionary.
 function GenericDictionary() 
 {	   
    Samples.AspNet.TestService.GetGenericDictionary(); 
 }

 // Get a generic Dictionary of custom types. 
 function GenericCustomTypeDictionary() 
 {	   
    Samples.AspNet.TestService.GetGenericCustomTypeDictionary(); 
 }


 // Pass a generic dictionary of custom types
 // to Webservice.
 function PassGenericDictionary() 
 {	   

    var simple = new Samples.AspNet.SimpleClass2();
    simple.s = "WebService proxy.";

    Samples.AspNet.TestService.PassGenericDictionary(
    {"first":simple}); 
 }

 // Get an Array.
 function ArrayType() 
 {	   
    Samples.AspNet.TestService.GetArray(); 
 }


// Callback function invoked when the call to 
// the Web service methods succeeds. 
function SucceededCallback(result, userContext, methodName)
{ 
    var message;
    switch(methodName)
    {
        case ("GetGenericList"):
        {
            var i = 0;
            var message = new Array();
            for(var item in result)
            {    
               message[i] = "List element " + i + ": " + result[item].s;
               i++;
            }
            DisplayMessage(message.toString());
            break;
        }


        case ("GetGenericDictionary"):
        {
            var i = 0;
            var message = new Array();
            for(var item in result)
            {    
               message[i] = item + ": " + result[item];
               i++;
            }
            DisplayMessage(message.toString());
            break;
        }

        case ("GetGenericCustomTypeDictionary"):
        {
            var i = 0;
            var message = new Array();
            for(var item in result)
            {    
               message[i] = item + ": " + result[item].s;
               i++;
            }
            DisplayMessage(message.toString());
            break;
        }

        case ("PassGenericDictionary"):
        {

            DisplayMessage(result);

            break;
        }

        case ("GetArray"):
        {
            var i = 0;
            var message = new Array();
            for(var item in result)
            {    
               message[i] = result[item];
               i++;
            }
            DisplayMessage(message.toString());
            break;
        }

        default:
        {
            DisplayMessage("Method unknown");
        }
    }       
}

// Callback function invoked when the call to 
// the Web service methods fails.
function FailedCallback(error, userContext, methodName) 
{
    if(error !== null) 
    {
        displayResult.innerHTML = "An error occurred: " + 
            error.get_message();
    }
}

function DisplayMessage(message)
{
    if (document.all) 
        displayResult.innerText = message;
    else
        // Firefox
        displayResult.textContent = message;    
}



if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();



The next part of the example shows the Web service that is called by the page.

<%@ WebService Language="C#" Class="Samples.AspNet.TestService" %>

namespace Samples.AspNet
{
    using System;
	using System.Collections;
	using System.Collections.Generic;
    using System.Web.Services;
    using System.Web.Script.Services;

	// Custom type used by WebService.
	public class SimpleClass
	{
        private string _s = "SimpleClass1";
	
       	public String s {
                    get { return _s; }
            		set { _s = value; }
        }
	}

    // Custom type used by WebService.
    public class SimpleClass2
    {
        private string _s = "SimpleClass2";

        public String s
        {
            get { return _s; }
            set { _s = value; }
        }
    }

    // The following service allows the generation
    // of the SimpleClass2 type proxy by applying the
    // attribute: GenerateScriptType. This assures
    // that the a SimpleClass2 object can be 
    // passed by the client script to the 
    // PassGenericDictionary method.
    // Note if you comment out the GenerateScriptType
    // you get an error because the SimpleClass2 type proxy
    // is not generated.
	[WebService(Namespace = "http://tempuri.org/")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [GenerateScriptType(typeof(SimpleClass2))]
	[ScriptService]
	public class TestService : System.Web.Services.WebService
	{
        // The following method return a list of SimpleClass
        // objects.
        // Note the SimpleClass type proxy is automatically 
        // generated because used in the return parameter.
		[WebMethod]
		[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
		public List<SimpleClass> GetGenericList() 
        {
            List<SimpleClass> GetGenericList = new List<SimpleClass>();
            SimpleClass simple1 = new SimpleClass();
            SimpleClass simple2 = new SimpleClass();
            simple1.s = "Generics first instance";
            simple2.s = "Generics second instance";
            GetGenericList.Add(simple1);
            GetGenericList.Add(simple2);
            return GetGenericList;
        }

        // The following method return a Dictionary of strings.
        [WebMethod]
        public Dictionary<String, String> GetGenericDictionary()
        {
            //Instantiate the dictionary object.
            Dictionary<String, String> result = 
                new Dictionary<string, string>();

            //Add items.
            result.Add("0000FF", "Blue");
            result.Add("FF0000", "Red");
            result.Add("00FF00", "Green");
            result.Add("000000", "Black");

            return result;
        }

        // The following method return a Dictionary of 
        // SimpleClass objects.
        // Note the SimpleClass type proxy object is automatically 
        // generated because used in the return parameter.
        [WebMethod]
        public Dictionary<String, SimpleClass> GetGenericCustomTypeDictionary()
        {
            //Instantiate the dictionary object.
            Dictionary<String, SimpleClass> result =
                new Dictionary<string, SimpleClass>();

            SimpleClass simple = new SimpleClass();
            simple.s = "custom type instance";

            //Add items.
            result.Add("Custom type", simple);

            return result;
        }

        // The following method accept a Dictionary of 
        // SimpleClass2 objects.
        // Note the SimpleClass2 type proxy object is 
        // not automatically generated because used in 
        // an input parameter. You must enable its 
        // generation by applying the GenerateScriptType 
        // attribute to the service.
        [WebMethod]
        public String PassGenericDictionary(
            Dictionary<string, SimpleClass2> d)
        {

            string value = d["first"].s;

            string message = "Dictionary element value: " + value;

            return message;
        }


        // This function returns an array.
        [WebMethod]
        public ArrayList GetArray()
        {
            //Instantiate the array object.
            ArrayList result = new ArrayList();

            //Add items.
            result.Add("First element: " + "Test1");
            result.Add("Second element: " + "Test2");

            return result;
        }          
		
	}

}


Passing Parameters Typed as Enumerators

An enumerator type can be accessed by using the automatically generated proxy class.

NoteNote:

Do not instantiate the generated proxy class in order to access the enumerators.

The following example shows how to call a Web service method from client script when the parameters are typed as enumerators. The first part of the example shows a Web page that calls a Web service by using client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the Web page to call the Web service.

// ServerTypes.js

// The Web service default color.
var defaultRgb;

// The page feedback display element.
var displayResult;

// Gets the Web service selection list colors 
// and the default color.
function pageLoad() 
{
    // Get page feedback display element.
    displayResult = 
        document.getElementById("ResultId");

    // Assign default values for the generated proxy using
    // the (generated) static proxy.
    Samples.AspNet.ServerTypes.set_timeout(200);
    Samples.AspNet.ServerTypes.set_defaultUserContext("Default context");
    Samples.AspNet.ServerTypes.set_defaultSucceededCallback(SucceededCallback);
    Samples.AspNet.ServerTypes.set_defaultFailedCallback(FailedCallback);

}

// This function shows how to get an 
// enumeration object from the server.
function GetFirstEnumElement()
{
    // Get the first element of the enumeration
    Samples.AspNet.ServerTypes.GetFirstColor();
}

// This function shows how to pass an 
// enumeration value to the server.
function GetSelectedEnumValue()
{
   // Get the value of the selected enumerated
   // element.
   Samples.AspNet.ServerTypes.GetSelectedColor(
    Samples.AspNet.ColorEnum.Blue);
}

// Callback function invoked when the call to 
// the Web service methods succeeds.
function SucceededCallback(result, userContext, methodName)
{ 
    var message;
    switch(methodName)
    {
        case ("GetFirstColor"):
        {
            var firstColor = result;
            message = "First enumerated value: " + firstColor;
            DisplayMessage(message);
            break;
        }

        default:
        {
            DisplayMessage("Method unknown");
        }
    }       
}

// Callback function invoked when the call to 
// the Web service methods fails.
function FailedCallback(error, userContext, methodName) 
{
    if(error !== null) 
    {
        displayResult.innerHTML = "An error occurred: " + 
            error.get_message();
    }
}

function DisplayMessage(message)
{
    if (document.all) 
        displayResult.innerText = message;
    else
        // Firefox
        displayResult.textContent = message;    
}



if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();



The next part of the example shows the Web service that is called by the page.

No code example is currently available or this language may not be supported.

The Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It supports ASP.NET AJAX and the JavaScript Object Notation (JSON) data format. This enables WCF services to expose operations to Web pages that run JavaScript code and that can therefore access these services by using HTTP requests.

If you have already created WCF services, you can add endpoints to enable script in your AJAX enabled Web pages to access the same service.

Calling a Windows Communication Foundation (WCF) service operation (which is a WCF term for a method) from script is asynchronous. As with other asynchronous procedures, you provide a succeeded callback function that is invoked when the request has finished. You can also provide a failed callback function to handle errors. For more information about Windows Communication Foundation (WCF) services and hosting them in ASP.NET, see ASP.NET AJAX Integration and JSON Support.

The following example shows how to build a WCF service and call its methods by using client script in a Web page script. The first part of the example shows how to make service calls through client script.

No code example is currently available or this language may not be supported.

The next part of the example shows the client script that is used by the Web page to call the Web service.

The next part of the example shows the Web service that is called by the page.

No code example is currently available or this language may not be supported.

Community Additions

ADD
Show: