Книга: C# 2008 Programmer

Calling WCF Services from an AJAX Page

Calling WCF Services from an AJAX Page

Visual Studio 2008 includes the new AJAX-enabled WCF Service template that enables you to consume WCF services, using AJAX. To try it out, use Visual Studio 2008 to create a new ASP.NET Web Application project. Name the project AJAXWCF (see Figure 20-44).

Figure 20-44

Right-click the project name in Solution Explorer, and select Add New Item (see Figure 20-45).

Figure 20-45

Select the AJAX-enabled WCF Service template (see Figure 20-46), name it Service.svc, and click Add.

Figure 20-46

Notice that Visual Studio 2008 automatically inserts the <system.serviceModel> element into the Web.config file:

    <behavior name="ServiceAspNetAjaxBehavior">
   aspNetCompatibilityEnabled="true" />
   <service name="Service">
    <endpoint address=""
     binding="webHttpBinding" contract="Service"/>

In the Service.cs file located in the App_Code folder, give the service a namespace of "WCFService", and code the following GetServerTime() method:

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
[ServiceContract(Namespace = "WCFService")]
[AspNetCompatibilityRequirements(RequirementsMode =
public class Service {
 // Add [WebGet] attribute to use HTTP GET
 public void DoWork() {
  // Add your operation implementation here return;
 public DateTime GetServerTime() {
  return DateTime.Now;

In the Source view of Default.aspx, add the following highlighted code:

<form runat="server">
  <asp:ScriptManager runat="server">
    <asp:ServiceReference Path="~/Service.svc" />
 <input type="button" value="Get Server Time"
 <div />

This adds an instance of the <ScriptManager> control to the page and references the WCF service (Service.svc). It also adds a Button control to the page.

Insert the following JavaScript code into Default.aspx:

 <script language="javascript" type="text/javascript">
  function Button1_onclick() {
  function CallBackFunction(result) {
   $get("result").innerHTML = result;
 <form runat="server">

The Button1_onclick() JavaScript function is invoked when the button on the page is clicked. It calls the WCF service and the returning result is retrieved via the CallBackFunction() function.

Press F5 to debug the application. You can now click the Get Server Time button to obtain the server time without causing a refresh on the web page (see Figure 20-47).

Figure 20-47

Оглавление книги

Генерация: 1.270. Запросов К БД/Cache: 3 / 1
Вверх Вниз