Published on: 22 Oct, 2013

How to post JSON data to webservice using Jquery in ASP.Net C#?

Tumblr Digg Google Plus

In my previous tutorial, I have shown you on how to post data to webservice in Jquery using generic handler in C#. You can check it out previous article by clicking this link "Post json data to generic handler in C#"

In this tutorial, you will learn how to post data to webservices in C# and read the response back using JQuery. Lets say you want to post a data that contains your name and email. Let's examine the following html inputs table demo.

<table>
	<tr>
    	<td>Name</td>
        <td><input type="text" id="txtName" value="My Name"/></td>
    </tr>
    <tr>
    	<td>Email</td>
        <td><input type="text" id="txtEmail" value="sample@example.com"/></td>
    </tr>
    <tr>
    	<td></td>
        <td><input type="button" id="btnSubmit" value="Submit"/></td>
    </tr>
</table>
<p>The result after you submitted the data will appear below. </p>
<div id="result"></div>

In this example, we will post a basic user information containing name and email values and we will return a response return from server and display the response data in the result tag.

What we want to do is after the user click the Submit button, we want to post the data to a webservice that will accept two strings in this example, which will be Name and Email. Please see the sample of webservice written in C#. Let's create a webservice (asmx) and named it to TestWebService.asmx. Remember if we want to allow webservice to be called from javascript we have to add ScripService as shown below example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for TestWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class TestWebService : System.Web.Services.WebService {
    public TestWebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string GetPersonData(string name, string email) {
        return "You have submitted data with Name: " +  name +  " and Email: "  + email;
    }
}

We now have completed the basic webservice that will accept two strings. Let's create the JQuery function to submit the data.

//we bind the submit button, only bind after the page has been fully loaded.
$(function(){
	//we bind the button with click event
	$("#btnSubmit").click(function(){
    	//we create the json string
        var jsonData = JSON.stringify({
            'name': $("#txtName").val(),
            'email': $("#txtEmail").val()
        });
        
        $.ajax({
            type: "POST",
            url: "/TestWebService.asmx/GetPersonData",
            data: jsonData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (xhr, status, error) {
                //alert the error if needed
                $("#result").html("Sorry there is an error: " + xhr.responseText);
            },
            success: function (responseData) {
            	//show the response data from webservice. Note: the d represent the object property data passed by webservice. It can an object of properties or just single property
                $("#result").html(responseData.d);
            }
        });
    });
});

That's all we need. Pretty simple right?

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.