This tutorial will show you how to create and implement an AJAX-enabled WCF Service into an ASP.NET Web page. WCF (or Windows Communication Foundation) is a union of technologies developed by Microsoft to make it easier and quicker for developers to build distributed applications.

We are going to create a single web page that will allow the input of two numbers from the user, then we will access a WCF Service to make a calculation and return the value back to the Web Page. We will do this using AJAX so that we will get a near-instant response.

To start, create a new Web Application in Visual Studio 2008, and then in Solution Explorer, right-click the Project, choose Add New Item.. AJAX-enabled WCF Service. Name it Service1.svc – you will see that it is added to the Solution Explorer, along with a Service1.vb in the App_Code folder. The .vb file should open upon creation, and look something like this:

This is where we will add our logic to perform the calculation We will add a method to add two numbers together, like so:

Notice we specify a static method, and the OperationContract attribute defines it as an operation of this Service.
Now if we move to our ASPX page, we will want to add a ScriptManager to the page to manage all of our AJAX calls behind the scenes. But in order for our Service method to be accessible at page level, we will need to add a Service reference to our WCF Service. We do so like this:

Nothing much different to a regular ASP.NET Web Application here. Notice we include the handler for the button. Here we are calling a JavaScript function, which we can now add to the page. Add the following to the bottom of the page:

Here, we are directly referencing the public method we created within the WCF Service. We have access to this via JavaScript because we are using the ScriptManager to expose the Service to page level. We get the response from the method and display it in a JavaScript alert window. We have no need to write any code-behind logic, as all of the functionality is being handled by the Service. We can expand this Web Application by creating more methods (Operation Contracts) in the Service, and then referencing them in the same way via JavaScript.
Our entire Service code looks like this:

Our ASPX page will look something like this:

Download Source Files