CRUD Operations using WCF RESTful Service – Part 2

By | January 8, 2014

In previous part of this WCF Tutorial, 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 REST based service 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 of this WCF Application Tutorial series. 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.

Note: For this implementation, my focus is to provide you with jQuery code for calling a WCF RESTful Service for all CRUD (Create | Retrieve | Update | Delete) operations. So to avoid UI complications, I am preparing the data object for CREATE and UPDATE operations inside the code instead of using User Interface form. You can implement that in your own way and according to your need but jQuery AJAX call for all CRUD operations to WCF REST based Service will remain same.

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.RESTfull GET All
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.RESTfull Get By ID
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:RESTfull Create New

RESTfull UPDATE

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.RESTfull DELETE

For this WCF Tutorial, 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).

Top 10 Interview Questions and Answers Series:

Category: Uncategorized Tags: ,

About IMRAN ABDUL GHANI

Imran Abdul Ghani is working as Software Developer(Senior) with extensive knowledge in Web development technologies especially C#, ASP.NET, MVC, WCF, Web API, ADO.NET Entity Framework, jQuery etc. He has several 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 www.webdevelopmenthelp.net, www.topwcftutorials.net, and www.sharepointfordummies.net.

  • Alfonso Vázquez

    You have to do it with the code provided: the different javascript/jquery functions to get, add, update, or delete books.

    Make an empty web application (the client app), add a webform, and in it, the html with the table. Add some buttons to call the functions, and add the jquery functions in the tag .

    It is all

    Regards

    Code for the caller.aspx:

    //GET ALL
    function getAllBooks()
    {

    $.ajax({
    type: “GET”,

    url: “http://localhost:xxxx/BookService.svc/Books/”,
    contentType: “json”,
    dataType: “json”,
    cache: false,

    success: function(data)
    {

    $.each(data, function (key, value)
    {
    var jsonData = JSON.stringify(value);
    //var jsonData = JSON.stringify(data);
    var objData = $.parseJSON(jsonData);
    var bookId = objData.BookId;
    var isbn = objData.ISBN;
    var title = objData.Title;

    $(” + bookId + ” + isbn + ” + title + ”).appendTo(‘#books’);
    });

    },
    error: function (xhr)
    {

    alert(xhr.responseText);

    }

    });
    }

    //GET ID
    function getBookById()
    {

    var id = document.getElementById(“TextId”).value;
    $.ajax({
    type: “GET”,
    url: “http://localhost:xxxx/BookService.svc/BookById/” + id,
    contentType: “json”,
    dataType: “json”,
    cache: false,
    success: function (data)
    {
    var jsonData = JSON.stringify(data);
    //Parse JSON
    var objData = $.parseJSON(jsonData);
    var bookId = objData.BookId;
    var isbn = objData.ISBN;
    var title = objData.Title;

    $(” + bookId + ” + isbn + ” + title + ”).appendTo(‘#books’);
    },
    error: function (xhr)
    {
    alert(xhr.responseText);
    }

    });
    }

    //CREATE
    function addNewBook()
    {

    var isbn = document.getElementById(“TextISBN”).value;
    var title = document.getElementById(“TextTitle”).value;

    var bookData = {
    “BookId”: 0,
    “ISBN”: isbn,
    “Title”: title
    };

    $.ajax({
    type: “PUT”,
    url: “http://localhost:xxxx/BookService.svc/AddBook/”,
    data: JSON.stringify(bookData),
    contentType : “application/json; charset=utf-8”,
    dataType: “json”,
    processData: true,
    cache: false,
    success: function(data, status, jqXHR){
    alert(“success…” + data);
    },
    error: function(xhr){
    alert(xhr.ResponseText);
    }

    });
    }

    //UPDATE
    function updateBook()
    {
    var id = document.getElementById(“TextId”).value;
    var isbn = document.getElementById(“TextISBN”).value;
    var title = document.getElementById(“TextTitle”).value;

    var bookData = {
    “BookId”: id,
    “ISBN”: isbn,
    “Title”: title
    };

    $.ajax({
    type: “PUT”,
    url: “http://localhost:xxxx/BookService.svc/UpdateBook/” + id,
    data: JSON.stringify(bookData),
    contentType: “application/json; charset=utf-8”,
    dataType: “json”,
    processData: true,
    cache: false,
    success: function (data, status, jqXHR)
    {
    alert(“success…” + data);
    },
    error: function (xhr)
    {
    alert(xhr.ResponseText);
    }
    });
    }

    //DELETE
    function deleteBook()
    {
    var id = document.getElementById(“TextId”).value;
    $.ajax({
    type: “DELETE”,
    url: “http://localhost:xxxx/BookService.svc/DeleteBook/” + id,
    contentType: “json”,
    dataType: “json”,
    cache: false,
    success: function (data)
    {
    alert(“success…” + data);
    },
    error: function ()
    {
    alert(xhr.ResponseText);
    }
    });
    }

    //SAVE

    function saveBook() {

    var bookData = {
    “BookId”: 0,
    “ISBN”: “32334833425543”,
    “Title”: “WCF RESTful Service by Example”
    };

    $.ajax({
    type: “POST”,
    url: “http://localhost:8369/BookService.svc/SaveBook/0”,
    data: JSON.stringify(bookData),
    contentType: “application/json; charset=utf-8”,
    dataType: “json”,
    processData: true,
    cache: false,
    success: function (data, status, jqXHR) {
    alert(“success…” + data);
    },
    error: function (xhr) {
    alert(xhr.responseText);
    }
    });
    }

    //RESET tabla
    function resetTabla()
    {
    //$(” + ” + ” + ”).appendTo(‘#books’);
    alert(“deleting”);
    $(“tr:gt(0)”).remove();
    }

    input{
    width: 150px;

    }
    table{
    width:300px;

    }

    ID:    

     
     

    ISBN: 
    Title:   

     

    Book ID
    ISBN
    Title

  • Alfonso Vázquez

    First of all, thank you for the tutorial, excellent.

    But, on one hand…I’ve got problems. I’ve made a client, but the software works fine in Internet Explorer, but not in Chrome. I’ve installed the Extensión Allow-Control-Allow-Origin for Chrome but it keeps not working.
    What can be the reason?

    On the other hand, I recommend you all to put in the $.ajax() method for the GetAllBooks() the parameter cache to false to refresh the return of the repository, this way:

    $.ajax({
    type: “GET”,
    url: “http://localhost:xxxx/BookService.svc/Books/”,
    contentType: “json”,
    dataType: “json”,
    cache: false,
    success: function(data)
    {
    alert(JSON.stringify(data));

    Thank you, again. Regards

  • Nowsath J

    THANKING YOU SO MUCH SIR..ITS BEST SITE FOR LEARN WCF..I SEARCHED IN MANY SITES.BUT HERE ONLY I FOUND SOLUTION WHAT I WANT EXACTLY :)

  • Vijay Seth

    where is the downloadable code for 2nd part.

  • Kopiraj

    Really very useful Tutorial.. Thank you very much.!!!

  • Akhil Kumar

    thank you very much….

  • chanchal

    hi , when i m calling getallbooks my jqury not gets error.

    please check my code

    function GetBookById()

    {

    $.ajax({

    type: “GET”,

    url: “http://localhost:3861/BookService.svc/Books/”,

    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;

    $(” + bookId + ” + isbn + ” + title + ”).appendTo(‘#books’);

    },

    error: function (xhr) {

    alert(xhr.responseText);

    }

    });

    }

  • http://facebook.com/ Jane

    One neat test client that I found for testing REST Services is WcfStorm.Rest (http://www.wcfstorm.com). You just give it a URL, press F5 and it goes invoke the service. You should check it out.

    • http://www.blogger.com/profile/10867674357364468276 Imran Ghani

      Thats right Jane. But its a test client. But when you need to call it from your own code, you need to understand and make the call using jQuery as given in this article.