TechBubbles Microsoft Technology BLOG

AJAX Enabled WCF Service


In .NET Framework 3.5 WCF supports returning JSON serialized data from REST-based Web Service. You can read REST Based WCF Service in ASP.NET 3.5 article to know about developing a REST Web Service. This post explains about creating a REST based Web Service that returns JSON-formatted data to ASP.NET page.

1.Create a new web site in VS20008 and Add a new item to the  App_Code folder by selecting the AJAX-enabled WCF Service template from the dialogue box as shown below


2. Add a new method named GetAllEmployee() to the above created class file as follows

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ServiceModel; using System.Runtime.Serialization; using System.Collections.Generic; using System.ServiceModel.Web; using System.ServiceModel.Activation; using System.Configuration; [OperationContract] [WebGet(UriTemplate = "/")] public EmployeeResults[] GetAllEmployee() { string strConnection = ConfigurationManager

.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString; DataClassesDataContext dc = new DataClassesDataContext(strConnection); string strUrl = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString(); var result = from anEmp in dc.employee select new EmployeeResults { EmployeeName = dc.emp_name; Link = string.Format("{0}{1}",currentURL,dc.emp_name); } return result.ToArray(); }





We need to write a LINQ to SQL class for returning the employee details from the entity by exposing some properties like emp_name.

3. Add a new item to the web site and select the AJAX Web Form as the Template and name the web form as ShowEmployee.aspx as follows


4. Expand the ScriptManager element, add a Services element and then add a ServiceReference element along with a Path attribute as follows.


The path attribute value for ServiceReference element is .svc file in the project.

5. Write the following code in the ShowEmployee.aspx file


We are getting the reference of an employee and loop through the results and then populating the list of employee in drop down. Notice that the results is JSON encoded version array.

6. You will also get the IntelliSense for the EmployeeJSONService  type inside the pageLoad() function.

7. View the ShowEmployee.aspx page in browser you will get the employee names in the drop down list.


This basic example explained about writing WCF service using AJAX code.

Share this post :

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.


TechBubbles Microsoft Technology BLOG

Follow me


Tag Cloud