Click here to Skip to main content
15,884,537 members
Articles / WCF

Post JSON Data to WCF RESTful Service using jQuery

Rate me:
Please Sign up or sign in to vote.
4.38/5 (9 votes)
7 Feb 2014CPOL2 min read 83.6K   14   2
Post JSON Data to WCF RESTful service using jQuery

The POST request method is basically designed to post data to a web server for storage. That's why it's 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. The 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 operations?

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 an 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 the 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:

C#
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:

JavaScript
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 the 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. Readers 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)


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

 
Bugset body Style Pin
zubaer23-Oct-15 22:14
zubaer23-Oct-15 22:14 
GeneralMy vote of 4 Pin
Christian Amado19-Mar-14 2:16
professionalChristian Amado19-Mar-14 2:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.