Click here to Skip to main content
Click here to Skip to main content
Go to top

Implement CRUD Operations using RESTful WCF Service and JavaScript

, 15 Sep 2011
Rate this:
Please Sign up or sign in to vote.
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.

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:

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:

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:

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

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.

 $.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.

 $.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.

$.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.

 $.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)

Share

About the Author

Shahriar Iqbal Chowdhury/Galib
Technical Lead
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

 
SuggestionExcellent article But..... Pinprofessional@AmitGajjar1-May-13 19:57 
GeneralRe: Excellent article But..... PinprofessionalShahriar Iqbal Chowdhury/Galib3-Aug-13 8:39 
Generalgood article...its simply superb.... Pinmemberprawinkumar13-Feb-13 2:22 
GeneralRe: good article...its simply superb.... PinprofessionalShahriar Iqbal Chowdhury/Galib3-Aug-13 8:37 
GeneralMy vote of 5 Pinmembermustika7513-Aug-12 18:15 
QuestionValidation please... PinmemberMember 69995822-Apr-12 23:53 
GeneralMy vote of 5 Pinmembermanoj kumar choubey23-Mar-12 0:51 
Question[My vote of 1] Needs C# and XML Pinmembertroybooth19-Mar-12 1:40 
GeneralMy vote of 5 PinmvpMd. Marufuzzaman7-Oct-11 21:05 
GeneralRe: My vote of 5 PinmemberShahriar Iqbal Chowdhury8-Oct-11 4:26 
Thanks, I am glad you like it Smile | :)
GeneralMy vote of 5 PinmemberWooters15-Sep-11 7:53 
GeneralRe: My vote of 5 PinmemberShahriar Iqbal Chowdhury15-Sep-11 9:33 
GeneralMy vote of 5 PinmemberMonjurul Habib14-Sep-11 11:39 
GeneralRe: My vote of 5 PinmemberShahriar Iqbal Chowdhury14-Sep-11 11:41 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 16 Sep 2011
Article Copyright 2011 by Shahriar Iqbal Chowdhury/Galib
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid