Click here to Skip to main content
Click here to Skip to main content

Post JSON data to WCF RESTful Service using jQuery

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

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.

So, 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, that's 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. Reader of this WCF tutorial might also be interested in:

License

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

About the Author

Imran Abdul Ghani
Software Developer (Senior)
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.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 4 PinpremiumChristian Amado19-Mar-14 2:16 

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.140721.1 | Last Updated 7 Feb 2014
Article Copyright 2014 by Imran Abdul Ghani
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid