In this article, we’ll discuss how to handle JSON encode and decode when passing JSON from client to server side and vice-versa using Asp.Net WebMethods.

We encode JavaScript object into JSON when we need to pass it from client side to server side. Decoding is done on the server side, so that the JavaScript object can be converted into a C# class object. Consider for instance that we need to collect a few details about an employee and pass it to the server side to a web method.

Also read : What is An Interface in C# and Why Use It ?

Handling JSON Encode

First, we’ll need to create a JavaScript function for the Employee as shown below:

function Employee(name, age, address) {
    this.EmpName = name;
    this.EmpAge = age;
    this.EmpAddress = address;
}

After we have collected the employee details we’ll create an instance of the Employee and pass this object over to the C# web method. Here is our C# web method.

[WebMethod]
public static void AddEmployee(Employee empData) {
    // empData contains the encoded Employee details
}

public class Employee {
    public string EmpName {
        get;
        set;
    }
    public Int32 EmpAge {
        get;
        set;
    }
    public string EmpAddress {
        get;
        set;
    }
}

As you can see the C# code also has a class quite similar to the JavaScript function. It’s required in order to decode the JSON object passed from client side. We’ll we calling the web method from client side using jQuery AJAX.

Given below is the jQuery Ajax code, about how to call the web method and pass the JSON data as parameter to C# web method.

if (name && age && address) {
    var emp = new Employee(name, age, address);

    $.ajax({
        type: 'POST',
        url: 'Index.aspx/AddEmployee',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            empData: emp
        }),
        success: function(reponse) {

        },
        error: function(error) {
            console.log(error);
        }
    });
}

The above code is pretty much self explanatory. We have created an instance of the Employee JavaScript function and passed in as parameter to the web method.

Two most common errors that I have encountered while trying to establish this web method are :

Invalid web service call, missing value for parameter:

which occurs when the JSON that you are passing doesn’t have the same parameter name as per the C# web method. Basically it means, if the web method is expecting a parameter called empData as the case is here, then the data passed from the jQuery AJAX should have the same parameter as

data: JSON.stringify({ empData: emp })

Another error which occurred was :

Unknown web method error

If you get this error then most probably, you are having the wrong web method name or else as was in my case the web method wasn’t declared static.

Now when the data is passed as JSON object it’s automatically decoded at the server side.

Handling JSON Decode

When sending data from server to client, we’ll pass data as C# object from the web method as shown below:

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetEmployee(Int32 empId) {
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Employee emp = new Employee();
    emp.EmpName = "Roy";
    emp.EmpAge = 25;
    emp.EmpAddress = "Delhi";
    return serializer.Serialize(emp).ToString();
}

In order to decode the JSON response to JavaScript object we’ll make use of JSON.parse as shown below:

$.ajax({
    type: 'GET',
    url: 'Index.aspx/GetEmployee',
    contentType: 'application/json; charset=utf-8',
    data: {
        empId: 1
    },
    success: function(response) {
        var arr = JSON.parse(response.d);
        console.log(arr);
    },
    error: function(error) {
        console.log(error);
    }
});

Things to note above are that we have used JavaScript serializer to serialize data from C# Object to proper JSON in the web method.

Ending Note

In this article, we discussed and saw how to handle JSON encode and decode. Using the above code I have created a sample app which show the process of encoding and decoding the JSON.

Source code is available at GitHub.

For a bit more info on JavaScript JSON have a look at the JavaScript JSON Array.