Click here to Skip to main content
15,890,825 members
Articles / WCF

CRUD Operations using WCF RESTful Service - Part 2

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
9 Jan 2014CPOL3 min read 10K   4  
In this part, we will write and understand code to consume the RESTful web service using jQuery.

In the 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. As in the previous part, I will write the 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 the following jQuery code.

In order to display the data returned from REST WCF Service, I have added HTML table to the body of the page.

HTML
 <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 makes a call to our RESTful web service to fetch all books.

HTML
 // 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 the same verb on WebInvoke attribute while defining service contract for GetBookList service method.

The second important thing is URL "http://localhost/RESTServiceCRUD/BookService.svc/Books/".

In order to understand it, we can break up the above URL into two parts as:

  • http://localhost/RESTServiceCRUD/BookService.svc is a 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 understands UriTemplate, not the exact method name.

The third and last input parameter is "Content-Type". It's sent with request header to tell the server 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.

HTML
 //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:

JavaScript
 //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);
               }
     });
}
JavaScript
  //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 the following example, we are going to delete a book with Id = 2.

HTML
//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)


Written By
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.

Comments and Discussions

 
-- There are no messages in this forum --