Click here to Skip to main content
15,860,859 members
Articles / Web Development / ASP.NET

Implement CRUD Operations using RESTful WCF Service and JavaScript

Rate me:
Please Sign up or sign in to vote.
4.87/5 (24 votes)
15 Sep 2011CPOL5 min read 135.4K   11.4K   137   16
Easy way to consume WCF REST services through JQuery and perform CRUD (Create Retrieve Update Delete) operations

Introduction

Windows Communication Foundation (WCF) data service exposes data layers in a REST-ful manner and provides a really easy way for AJAX applications and other client-side applications to access the data, without having to go through the effort of writing an entire Web service. This caught my interest to play around with WCF. And through this post, we will see an approach to utilize entity framework and WCF data service to carry out CRUD operation with minimum effort.

REST Basics

Representational state transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. The cool thing about REST is that it is not tied to any particular technology or platform. The term is often used in a looser sense to describe any simple interface which transmits domain-specific data over HTTP without an additional messaging layer such as SOAP or session tracking via HTTP cookies. A RESTFul web service is a simple web service implemented using HTTP and the principles of REST. Such a web service can be thought about as a collection of resources.The MIME type of the data is supported by the web service. This is often JSON , XML or YAML but can be anything. The set of operations are supported by the web service using HTTP methods (e.g. POST, GET, PUT or DELETE).

WCF Rest Services

WCF Rest Services are normal WCF Services that have added functionality so that they can be consumed in a RESTful manner (URI vs URL, usage of HTTP Verbs, usage of different Data Transfer Formats like JSON, YAML, etc). The table below will help you to understand how the HTTP verbs are typically used to implement a web service.

Method Description
GET Requests a specific representation of a resource 
PUT Creates or updates a resource with the supplied representation
DELETE Deletes the specified resource
POST Submits data to be processed by the identified resource
HEAD Similar to GET but only retrieves headers and not the body
OPTIONS Returns the methods supported by the identified resource

Configure the WCF Service

It’s time to configure the WCF data service. Though we need entity framework 4 for this example, but I believe configuring entity framework is out of context of this post. So we will stick to configuring WCF data service only. In Solution Explorer, right-click the name of your ASP.NET project, and then click Add New Item. In the Add New Item dialog box, select WCF Data Service.

Image 1

For the name of the service, I choose EFService.svc. Visual Studio will show you some generated code. You’ll need to add the name of your Entity Framework Data Context in the definition of the WCF Data Service, for this particular example I am using SocialShareDatabaseContext like below:

C#
public class EFService : DataService<SocialShareDatabaseContext>

Use Visual Studio development server to test the service, which shall be like http://localhost:[port]/EFService.svc/Members //Gets all members. If you open the EFService.svc.cs in the attached sample project, you will see the code below:

Image 2

Also in web.config, at the bottom you will see 2 sections automatically added, one is: <system.webServer> and another one is <system.serviceModel> like below:

Image 3

Using WCF Rest Services from Client Side

WCF Data Services enable you to provide dynamic access to entity data in an XML format that can be used by applications. You can return XML (default), JSON from WCF REST services. There are a couple of ways to consume REST services from client side, but as a JQuery fan I will stick to it. Before taking the dive, JQuery ajax call requires some parameters that we need to know first, type: type of REST method to invoke, i.e., POST/GET/PUT/DELETE.

  • url: WCF service URL which are called by their URL plus the method name/entity name appended in the URL's extra path
  • data: Optional parameter, requires if invoking method/entity expects parameter.
  • contentType: When sending data to the server, use this content-type
  • dataType: returned data type, i.e. XML, JSON, etc.
  • success: A function to be called if the request succeeds, REST service will return JSON/XML if successful.
  • error:A function to be called if the request fails

Image 4

Now we will see how to invoke the WCF services with different REST methods.

Using GET Method

List the URIs and perhaps other details of the collections. In our case, requests collection of members.

JavaScript
$.ajax({
           type: "GET",
           url: "Services/EFService.svc/Members",
           data: "{}",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (data) {
               // Play with returned data in JSON format
           },
           error: function (msg) {
               alert(msg);
           }
       });

Using POST Method

Retrieve a representation of the addressed member of the collection, in the example below, create a new entry in the collection.

JavaScript
$.ajax({
        type: "POST",
        url: "Services/EFService.svc/Members/",
        data: "{Email:'test@test.com', ScreenName:'TestUser'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
          // Play with response returned in JSON format
        },
        error: function (msg) {
            alert(msg);
       }
   });

Using PUT Method

Update the entire collection with another collection, in the example below, update the addressed member of the collection.

JavaScript
$.ajax({
         type: "PUT",
         url: "Services/EFService.svc/Members/",
         data: "{Email:'test@test.com', ScreenName:'TestUser'}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (data) {
           // Play with response returned in JSON format
         },
         error: function (msg) {
             alert(msg);
         }
     });

Using DELETE Method

Delete the entire collection or a specific collection, in the example below, delete Member with id=1.

JavaScript
$.ajax({
          type: "DELETE",
          url:  "Services/EFService.svc/Members(1)",
          data: "{}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (data) {
              // Play with response returned in JSON format
          },
          error: function (msg) {
              alert(msg);
          }
      });

Using the Sample Code

Using the attached sample code requires:

  • VS2010 with service pack 1 installed
  • Microsoft SqlServer 2005 or later
  • Basic understanding of Entity Framework 4.0

Configure your environment:

  • Attach the sample.mdf and sample.ldf
  • Those who want to use sqlserver 2005, download DbSchema-SQLServer2005.zip from top and unzip. Create a database name sample and run the unzipped SQL script
  • Open web.config and find connectionStrings section and edit the connection string according to your local SQL Server login credential 

For tabular data display purposes, I used JQuery template plugin to render collection. Run default.aspx page to see the sample.

History

  • Version 1.0: Basic version updated
  • Version 1.1: Database schema for Microsoft SqlServer 2005 attached

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
Bangladesh Bangladesh
I am a Software Engineer and Microsoft .NET technology enthusiast. Professionally I worked on several business domains and on diverse platforms. I love to learn and share new .net technology and my experience I gather in my engineering career. You can find me from here

Personal Site
Personal Blog
FB MS enthusiasts group
About Me

Comments and Discussions

 
QuestionService method look like Pin
lakshan Sakila21-Feb-17 0:13
lakshan Sakila21-Feb-17 0:13 
Questionquerstion Pin
pop ioana19-Mar-15 0:05
pop ioana19-Mar-15 0:05 
SuggestionExcellent article But..... Pin
AmitGajjar1-May-13 19:57
professionalAmitGajjar1-May-13 19:57 
GeneralRe: Excellent article But..... Pin
Shahriar Iqbal Chowdhury/Galib3-Aug-13 8:39
professionalShahriar Iqbal Chowdhury/Galib3-Aug-13 8:39 
Generalgood article...its simply superb.... Pin
prawinkumar13-Feb-13 2:22
prawinkumar13-Feb-13 2:22 
GeneralRe: good article...its simply superb.... Pin
Shahriar Iqbal Chowdhury/Galib3-Aug-13 8:37
professionalShahriar Iqbal Chowdhury/Galib3-Aug-13 8:37 
GeneralMy vote of 5 Pin
mustika7513-Aug-12 18:15
mustika7513-Aug-12 18:15 
QuestionValidation please... Pin
NameFlorin2-Apr-12 23:53
NameFlorin2-Apr-12 23:53 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey23-Mar-12 0:51
professionalManoj Kumar Choubey23-Mar-12 0:51 
Question[My vote of 1] Needs C# and XML Pin
msdevtech19-Mar-12 1:40
msdevtech19-Mar-12 1:40 
GeneralMy vote of 5 Pin
Md. Marufuzzaman7-Oct-11 21:05
professionalMd. Marufuzzaman7-Oct-11 21:05 
GeneralRe: My vote of 5 Pin
Shahriar Iqbal Chowdhury/Galib8-Oct-11 4:26
professionalShahriar Iqbal Chowdhury/Galib8-Oct-11 4:26 
GeneralMy vote of 5 Pin
Wooters15-Sep-11 7:53
Wooters15-Sep-11 7:53 
GeneralRe: My vote of 5 Pin
Shahriar Iqbal Chowdhury/Galib15-Sep-11 9:33
professionalShahriar Iqbal Chowdhury/Galib15-Sep-11 9:33 
GeneralMy vote of 5 Pin
Monjurul Habib14-Sep-11 11:39
professionalMonjurul Habib14-Sep-11 11:39 
GeneralRe: My vote of 5 Pin
Shahriar Iqbal Chowdhury/Galib14-Sep-11 11:41
professionalShahriar Iqbal Chowdhury/Galib14-Sep-11 11:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.