Calling Web Services from Client Script

Web services can be called from client scripts, such as Javascript too. This is most useful for example if you need to expose a database result set to your javascipt client code. Both XML Web services and WCF services can be called from client script. The steps are essentially the same for both scenarios.

First you must expose your service to be consumable from client script. For a standard XML Web service, add the ScriptServiceAttribute to your .asmx.cs file. If you work from template, you just need to uncomment the line. Your result would look like this:

ScriptService1

To set up a WCF service, you should ensure of the following:

  1. The service must be hosted by a web application within a .svc file. You will need to point to this file later.
  2. You must configure the web application to support service calls from client script.

To configure the web application, you need to do the following:

  1. In the web.config, set the aspnetCompatibilityEnabled attribute of the serviceHostingEnvironment property to true.
  2. Set up the binding and service behaviors.
  3. Add an endpoint.

Your web.config should look like this when you’ve done:

ScriptService2

To consume the service from client script, you should add a ScriptManager control to your client page. Then define a Services tag inside of it, and add ScriptReferences for the scripts you want to include. A ScriptReference can have two attributes, a Path and an InlineScript property. The Path should be set to the .asmx or .svc file (depending on the type of service you are using). The InlineScript is set to false by default, set it to true when the proxy code of your service is defined in the same page. An example:

ScriptService3

Now you should define the client-side javascript code which consumes the service. Service calls from scripts are essentially asynchronous callbacks. You can provide a successful callback option, an error callback option, and the values you’d like to pass to your service method. An example service call looks like this:

function CallService(value)

{

    ServiceName.MethodName(value, onSuccess, onFail);

}

function onSuccess(result)

{

    alert(result);

}

function onError(error)

{

    alert(error.get_message);

}

Further Readings

Exposing WCF Services to Client Script

Calling Web Services from Client Script

Using Web Services with ASP.NET AJAX

Creating and Using AJAX Enabled Web Service

Configure WCF Services in ASP.NET AJAX

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s