Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

CRUD Operations using WCF RESTful Service - Part 2

, 9 Jan 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
In previous part of this article, we created a WCF RESTful service step by step and make it available to be consumed by a client. Here in this part, we will write and understand code to consume the RESTful web service using jQuery. Same like previous part, I will write complete jQuery code for all C
In previous part of this article, we created a WCF RESTful service step by step and make it available to be consumed by a client. Here in this part, we will write and understand code to consume the RESTful web service using jQuery. Same like previous part, I will write complete jQuery code for all CRUD operations instead of leaving something for the reader.

One of the advantages of using RESTful web services is that it can be consumed by a wide range of client applications. Following is the jQuery code for each CRUD operation call against WCF RESTful service created in part 1.

For the purpose of implementation, I have created a new ASP.NET project to existing solution and add an ASP.NET Web Form to make calls. But you can have your own choice of client implementation using following jQuery code.

In order to display the data returned from REST WCF Service, I have added HTML table to body of the page.
  <table border='1' id="books">
      <!-- Make a Header Row -->
      <tr>
           <td><b>Book ID</b></td>
           <td><b>ISBN</b></td>
           <td><b>Title</b></td>
      </tr>
  </table>


Here is the function that make a call to our RESTful web service to fetch all books.
   // GET ALL
   function GetAllBooks()
   {
        $.ajax({
                 type: "GET",
                 url: "http://localhost/RESTServiceCRUD/BookService.svc/Books/",
                 contentType: "json",
                 dataType: "json",
                 success: function (data) {

                     $.each(data, function (key, value) {
                         //stringify
                         var jsonData = JSON.stringify(value);
                         //Parse JSON
                         var objData = $.parseJSON(jsonData);
                         var bookId = objData.BookId;
                         var isbn = objData.ISBN;
                         var title = objData.Title;
                         $('<tr><td>' + bookId + '</td><td>' + isbn + '</td><td>' + title + '</td></tr>').appendTo('#books');
                     });
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
       });
   }
jQuery asynchronous HTTP Request is made with  type as "GET". It represents HTTP verb being used to make a call. We have used same verb on WebInvoke attribute while defining service contract for GetBookList service method.

Second important thing is URL"http://localhost/RESTServiceCRUD/BookService.svc/Books/".
In order to understand it, we can break up above URL into two parts as:
  • http://localhost/RESTServiceCRUD/BookService.svc is simple URL to our service file (.svc). 
  • /Books/  is what we define as UriTemplate in WebInvoke attribute of that particular method.
Note: You may have noticed that for in Part-1, method name in service contract was "GetBookList" but UriTemplate was "Books/". So, client only understand UriTemplate not the exact method name.

Third and last input parameter is "Content-Type". It's sent with request header to tell server that what kind of response is expected on client-side i.e. JSON.
On success, the output will be in the form of JSON, so just parse it and append rows to already entered html table.

"GetBookById" is another way of consuming RESTful service and getting a record by bookId.
   //GET
   function GetBookById()
   {
        $.ajax({
                 type: "GET",
                 url: "http://localhost/RESTServiceCRUD/BookService.svc/BookById/2",
                 contentType: "json",
                 dataType: "json",
                 success: function (data) {
                     //stringify
                     var jsonData = JSON.stringify(data);
                     //Parse JSON
                     var objData = $.parseJSON(jsonData);

                     var bookId = objData.BookId;
                     var isbn = objData.ISBN;
                     var title = objData.Title;

                     $('<tr><td>' + bookId + '</td><td>' + isbn + '</td><td>' + title + '</td></tr>').appendTo('#books');
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
   }
In this case the URL is "http://localhost/RESTServiceCRUD/BookService.svc/BookById/2". UriTemplate is "BookById" for service method "GetBookById" and "2" is the parameter for bookId.

Implementation for adding a new book or updating an existing record is as follows:
  //CREATE
  function AddNewBook()
  {
        var bookData = {
           "BookId": 0,
           "ISBN": "9483877388484",
           "Title": "Migration Strategies"
        };

        $.ajax({
                 type: "PUT",
                 url: "http://localhost/RESTServiceCRUD/BookService.svc/AddBook/0",
                 data: JSON.stringify(bookData),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
                     alert("success..." + data);
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
       });
  }

   //UPDATE
   function UpdateBook()
   {
       var bookData = {
          "BookId": 2,
          "ISBN": "9483877388484",
          "Title": "Migration Strategies"
       };

       $.ajax({
                 type: "PUT",
                 url: "http://localhost/RESTServiceCRUD/BookService.svc/UpdateBook/2",
                 data: JSON.stringify(bookData),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
                     alert("success..." + data);
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
        });
  }
For Create and Update, we create a JSON object and pass to jQuery Ajax as data parameter and type is "PUT" as Http verb.

Implementation for deleting a book. In following example we are going to delete a book with Id = 2.
//DELETE
         function DeleteBook() {
             $.ajax({
                 type: "DELETE",
                 url: "http://localhost/RESTServiceCRUD/BookService.svc/DeleteBook/2",
                 contentType: "json",
                 dataType: "json",
                 success: function (data) {
                     alert("successs.... " + data);
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
         }

For this article, I have provided the complete code and hopefully it will be very easy for readers to understand and implement CRUD operations for WCF RESTful service.

Previous - CRUD Operations using WCF RESTful Service - Part 1 (Creating WCF RESTful service).

Other related tutorials that might be of interest:

License

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

Share

About the Author

Imran Abdul Ghani
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET(MCSD.NET) since 2005. You can reach his blogging at WCF Tutorials, Web Development, SharePoint for Dummies.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150128.1 | Last Updated 9 Jan 2014
Article Copyright 2014 by Imran Abdul Ghani
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid