ASP.NET AJAX - Passing JSON Object from Client to Server
Part 1 - Calling Server Side methods 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
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.
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.
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