Skip to content


ASP.NET AJAX – Passing JSON object from client to server

  1. Part 1- Calling server side methods from client side

Read the Part 1 of this tutorial if you don’t know how to call server side methods directly from client side.

In this post, I will explain how to pass data from client to server in JSON format.

Microsoft AJAX client library has built-in methods which helps in serializing and de-serializing JSON. The methods are defined in "Sys.Serialization.JavaScriptSerializer" class. In server side we have "JavaScriptSerializer"that will help you out to do the JSON serialization and de-serialization.

With the help of these two classes, we can easily do the data transfer. Suppose you have class called "Customer" in server side, which looks like this

using System;

namespace ServerClientInteration
{
    [Serializable]
    public class Customer
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }
    }
}

This is our payload for this example, we are going to move this object from server to client and vice versa. For that I have exposed two static methods on the server side; one is for retrieving the customer details and the other is for updating the customer.

  public partial class _Default : System.Web.UI.Page
    {
        private static Customer customer = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (customer == null)
            {
                customer = new Customer();
                customer.ID = 1;
                customer.Name = "microsoft";
                customer.Address = "www.microsoft.com";
            }

        }

        [WebMethod]
        [ScriptMethod(UseHttpGet=true)]
        public static string GetTime()
        {
            return DateTime.Now.ToLongTimeString();
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public static string GetCustomer()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(customer);
        }

        [WebMethod]
        [ScriptMethod]
        public static string UpdateCustomer(string jsonCustomer)
        {
            try
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                Customer cust = serializer.Deserialize(jsonCustomer);
                customer.ID = cust.ID;
                customer.Name = cust.Name;
                customer.Address = cust.Address;

                return "Updated";
            }
            catch(Exception Exception)
            {

            }

            return "Error occured while updating";
        }
    }

In the above code, you can see "GetCustomer" and "UpdateCustomer" methods. "GetCustomer" will serialize the static customer object and return it as JSON string; "UpdateCustomer" method accepts JSON string as input and that string is de-serialized in to a customer object and the static customer variable is updated with the new values. "UpdateCustomer" will return status message after the update.

Usually, we persist the customer in DB or some other states, but here for simplicity I have used a static variable which will simulate the persistence.

Now we need to call this from the client-side, for that I have two hyperlinks; one will get the customer from the server and other send the customer to the server.

Here is how the HTML looks like

<head runat="server">
<title>Untitled Page</title>
<style type="text/css"> 

#result
{
width: 250px;
height: 300px;
overflow: auto;
border:1px solid #00d;
} 

</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
<a href="javascript:callServerMethod()" >Call Server method</a>
<hr />
<a href="javascript:getCustomer()" >Get Customer</a>
<div id="result"></div>
<hr />
<div>
ID : <input type="text" id="custID" /><br />
Name : <input type="text" id="custName" /><br />
Adress : <input type="text" id="custAdd" /><br />
</div>
<a href="javascript:updateCustomer()" >Update customer</a><br /> 

</div>
<script language="javascript" type="text/javascript">
//<![CDATA[ 

function callServerMethod()
{
PageMethods.GetTime(callBackMethod);
} 

function callBackMethod(result)
{
alert(result);
} 

function getCustomer()
{
PageMethods.GetCustomer(callBackGetCustomer);
} 

function callBackGetCustomer(result)
{
var customer = Sys.Serialization.JavaScriptSerializer.deserialize(result);
var content = "<br />ID :" +  customer.ID + "<br />" + "Name : " + customer.Name + "<br />" + "Address : " + customer.Address;
$get("result").innerHTML += content;
} 

var clientCustomer = function(id,name,add){
this.ID = id;
this.Name = name;
this.Address = add;
}; 

function updateCustomer()
{
var id = $get("custID").value;
var name = $get("custName").value;
var address = $get("custAdd").value; 

var customer = new clientCustomer(id,name,address);
var serializedCustomer = Sys.Serialization.JavaScriptSerializer.serialize(customer);
PageMethods.UpdateCustomer(serializedCustomer,callBackUpdateCustomer);
} 

function callBackUpdateCustomer(result)
{
alert(result);
} 

//]]>
</script>
</form>
</body>

I think the above code is self explanatory, let me know if you have any difficulty in understanding this.

Hope this will gave some idea about passing JSON between client and server. I have uploaded the source code in my server and you can get it from here – http://www.rajeeshcv.com/download/ServerClientInteration.zip

kick it on DotNetKicks.com

Posted in ASP.NET, JavaScript.


7 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Nicsam says

    Hi Rajeesh

    Very nice article on serializing – deserializing JSON objects.
    Keep on posting similar ones.

    Regards
    Nicsam

  2. Nicsam says

    Hi Rajeesh
    Once again i appreciate your effort to write one.
    Here i doubt to ask a point,is that possible to pass the JSON object without having the serialization and deserialization processes i.e.

    Like PageMethods.UpdateCustomer(Customer,callBackUpdateCustomer);
    here customer is just a object with values.

    In the server side omit the deserialization process.I hope this should work out.
    Please reply your thoughts.

  3. Rajeesh says

    Hi Nicsam,

    Thanks for the comments.

    Regarding the serialization – If you don’t serialize it, I don’t think it will work out unless the customer object is a string because the proxy pageMethods always expects string data type.

    When we do the serialization the JavaScriptSerializer converts the Customer object to a string object(JSON format) which is passed to the Page method.

    Regards,
    Rajeesh

  4. Nicsam says

    Hi

    But i got this worked.Please have a check follow the steps in your code you will get this

    1)Modify UpdateCustomer web method to
    public static string UpdateCustomer(Customer newCustomer)
    {
    Customer NewCustomer = newCustomer;
    return “Updated”;
    }

    2)Modify the client side function in your code as follows

    function updateCustomer()
    {
    var id = $get(“custID”).value;
    var name = $get(“custName”).value;
    var address = $get(“custAdd”).value;

    var customer = new clientCustomer(id,name,address);

    PageMethods.UpdateCustomer(customer ,callBackUpdateCustomer);
    }

    3)Try this across,hopes this should work.
    Please have a check and let me know your thoughts.

    Regards
    Nicsam

  5. Rajeesh says

    Hi Nicsam,

    Yes you are right, if we update the server method we don’t need to do the serialization/deserialization.

    Thanks for pointing out this.

    Regards,
    Rajeesh

  6. Nicsam says

    Hi

    This is SUJITH alias NICSAM… :-)

    Hey dude..HAPPY VISHU………

  7. Krishna Chaitanya says

    Nice article Rajeesh!
    I’ve been working on same topic and saw your article on Encosia.
    I have triend another approach which is handy. Check this:
    http://www.novogeek.com/post/2009/06/07/Passing-JSON-objects-in-NET-35.aspx



Some HTML is OK

or, reply to this post via trackback.