Consuming WCF Service using Client-Side AJAX in ASP.NET 3.5 and C#
Introduction
In this article, we will be looking at how we can use AJAX to implement a WCF Service, so that it's methods are available to client-side JavaScript. This is an extremely powerful tool, as we are able to access the WCF Service almost instantaneously, without posting back a page or waiting several seconds. In this example, we will create a basic ASPX page with a HTML form that will make use of JavaScript calls to the WCF Service we will create.
What we will learn in this article:
- How to Create an AJAX-Enabled WCF Service in Visual Studio.NET 2008;
- How to use JavaScript to make calls to the WCF Service.
Getting Started with our WCF Service
Let's get started by creating a new Web Application in Visual Studio 2008, and because we're working in ASP.NET 3.5, we have AJAX already built-in. The first thing to do is right-click the project in Solution Explorer, and choose to Add > New Item.. AJAX-enabled WCF Service. You should be presented with something like this:
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace WCF_UI
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
[OperationContract]
public void DoWork()
{
return;
// Add more operations here and mark them with [OperationContract]
}
Because Visual Studio will add the necessary references to our project and Web.config, we don't need to worry about these.
Next, we will create two methods, both with the [OperationContract] attribute. To demonstrate access to the methods, we will create a method to add two numbers together, and also one to subtract a number from another:
public Double Add(Double num1, Double num2)
{
[OperationContract]
public Double Subtract(Double num1, Double num2)
{
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
This is all for our Service. Now we can move to our ASPX page, and we will add a ScriptManager to the page. We will also need to reference the Service we just created, in order for us to access it via AJAX:
We just add a Service Reference to the Service we just created, which will allow us to access the methods of this Service within our code. Next, we will create a basic HTML form to allow the user to input numbers to use the addition method in our WCF Service:
Notice the onclick attribute we give to the button. This will reference a JavaScript function we will add to the page. Create a JavaScript block at the bottom of the page, and add the following:
function onAddSuccess(result) {