Mar 14, 2012

Posting client side variables to server using AJAX and Web Services in ASP.NET

1. Add reference to the  JSON.NET library
2. Import jQuery in the web-page
3. Import  JSON parser - by douglas crockford

Add a C# class in the web application project to represent posted entity data:
public class Customer
    string _firstName;

    public string FirstName
        get { return _firstName; }
        set { _firstName = value; }
    string _lastName;

    public string LastName
        get { return _lastName; }
        set { _lastName = value; }
    int _telephone;

    public int Telephone
        get { return _telephone; }
        set { _telephone = value; }
In the codebehind file of web page add a ‘public static’ method which accepts a parameter of type ‘object’, We need to make it static because it will be accessible without creating instance of the page class. More info
This method will process the data and return the result in string format

   //In Test.aspx.cs
    public static string AcceptData(object jsonData)
        Customer newCust =(Customer)JsonConvert.DeserializeObject(jsonData.ToString(),typeof(Customer));
        return "Server response: Hello "+newCust.FirstName;
Now, Lets write the ‘SendData’ function using which we will call the above ‘AcceptData’ web method from client side using JQuery AJAX
//javascript function in Test.aspx
function SendData() {
    //Build json object from values entered in form
    var newCustomer = {
        "FirstName": $("#txtFirstName").val(),
        "LastName": $("#txtLastName").val(),
        "Telephone": $("#txtTelephone").val()

    var jsonData = "{'jsonData':'" + JSON.stringify(newCustomer) + "'}";//create string representation of the js object

            //post data to server
                type: "POST",
                url: 'Test.aspx/AcceptData',
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: ($.browser.msie) ? "text" : "json",
                success: function(msg) {
                    //call successfull
                    var obj = msg.parseJSON();
                    alert(obj.d); //d is data returned from web services

                    //The result is wrapped inside .d object as its prevents direct execution of string as a script
                error: function(xhr, status, error) {
                    //error occurred
'jQuery.ajax()' function is used to asynchronously pass data to the server More Info

The web form
First Name:
Last Name:
Test Message
Download Source Code.rar

1. JSON.NET Codeplex Project: Manipulating JSON at server side
2. WebMethod attribute
3. jQuery: Javascript library
4. Manipulating JSON at client side

No comments:

Post a Comment

Be the first to comment on this post.