Friday, June 10, 2011

Calling WCF Web Services from JavaScript

Whenever you need to consume a WCF web service from a web page, you have (at least) three options:

Have the ASP.NET ScriptManager generate a strongly-typed JavaScript proxy to the service that you can call directly.
Use your own JavaScript, or some third party, library such as jQuery to invoke a service in REST style.
Use your own JavaScript to invoke a service using SOAP.

The first two require that you have control over the bindings specified in the Web.config file or the factory in the .svc file.


Call the service in JavaScript:

var svc = new WcfAjaxServices.TestService();

svc.GetTest('a', 'b',
function(result, context, functionName)
{
window.alert('A: ' + result.A);
},
function (error, context, methodName)
{
window.alert('error: ' + error);
}, null);


The methods look like the ones defined in the contract plus 3 additional arguments:
- a function to call in case of success
- a function to call in case of error
- an optional context

result and error are JavaScript objects
methodName is the name of the function that started the request.

Development With A Dot

No comments: