Post JSON data to WCF RESTful Service using jQuery

By | February 4, 2014

The POST request method is basically designed to post data to a web server for storage. That’s why its normally used when submitting a complete form. In this WCF RESTful service tutorial, I’ll try to explain how we can post JSON data to a WCF RESTful service using jQuery Ajax call with POST type. We discussed about “POST” HTTP verb in previous WCF tutorials but we didn’t use it in our implementation. Purpose of this article is to understand “POST” request with complete implementation for a specific operation.Earlier we discussed in detail that how to perform CRUD operations using WCF RESTful service and consume RESTful service using jQuery? We also discussed about different HTTP verbs (GET, POST, PUT, DELETE etc) and how these verbs map to different operation?

HTTP verb
Operation
GET
To get a specific resource.
PUT
Create or Update a resource.
DELETE
Delete a resource.
POST
Submit data to a resource.

MCSD Exam: 70-487So, here we are going to create a new resource using POST HTTP verb. We’ll not rewrite the complete code here instead we will reuse what we did in earlier tutorial. Let’s recap it here and continue.

  1. We have a DataContract class i.e. “Book”.
  2. a class BookRepository that implements an interface IBookRepository.
  3. RESTful service BookService implementing IBookService.
  4. and finally configuration related to our service.


First of all, we are going to add a service method “SaveBook” to our existing BookService. Add following method to IBookService interface.

        [OperationContract]
        [WebInvoke(Method = “POST”,
                    RequestFormat = WebMessageFormat.Json,
                    ResponseFormat = WebMessageFormat.Json,
                    UriTemplate = “SaveBook/{id}”)]
        string SaveBook(Book book, string id);
  • Method is the HTTP verb mapped here i.e. “POST”.
  • RequestFormat defines that request message format i.e. JSON in our example.
  • ResponseFormat represents response message format i.e. also JSON.
  • UriTemplate represents unique URI for this service operation.
BookService.cs implements the above operation as follows:
        public string SaveBook(Book book, string id)
        {
            Book newBook = repository.AddNewBook(book);
            return “id=” + newBook.BookId;
        }

Configuration settings for the BookService service will remain the same. No operation specific configuration required.

Now, we are going to consume this service using jQuery and call SaveBook service operation using jQuery Ajax POST as given below.

         function SaveBook() {

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

             $.ajax({
                 type: “POST”,
                 url: “http://localhost/RESTServiceCRUD/BookService.svc/SaveBook/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);
                 }
             });
         }

Few important notes about above code are:

  • jQuery makes an asynchronous HTTP request with type as “POST”. Remember while defining service operation, we use the same “POST” verb as method in WebInvoke attribute.
  • We created a JSON object i.e. bookData and pass it as parameter to data element.
  • URL is pointing to our BookService.svc plus “SaveBook/0”. While defining service operation, we use define it as “UriTemplate” in WebInvoke attribute.
    Note: As we are going to add a new book, thats why, pass “0” for id parameter.
  • processData, contentType and dataType are pretty simple.
When we run the above example, JSON object will be posted to WCF RESTful service and a new book will be added to our repository.
Enjoy programming.
Other Related Articles:

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.