Blog

USING JSON SERIALIZATION FOR CODE BEHIND-JAVASCRIPT DATA COMMUNICATION

By Jaish Mathews Blogs | Learn .NET Apr 14, 2010
Many of us went through a scenario like, can us pass a full of C# type/class to the javascript? Modify from there and again return back to C#? The difficulty is that JavaScript only knows string format comared to C# which has many data types. So how we can pass an entires class to JavaScript? Here we need to handle with JSON serialization techniques.

You need to add Ref to System.Web.Extensions.dll and also needed to add namespace
System.Web.Script.Serialization;
The code is simple as you only need to use a class named "JavaScriptSerializer". JSON converison of a simle class
Emloyee described below
//Class to be serialized in JASON
    public class Employee
    {
        public string ID
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
    }
//Code to perform above class to be serialized
    StringBuilder jasonSerialize = new StringBuilder();
            Employee emps = new Employee();
            emps.ID = "1";
            emps.Name = "Jaish";
            JavaScriptSerializer ser = new JavaScriptSerializer();
           
            ser.Serialize(emps, jasonSerialize);

The serialized information available in a stringbuilder varaible, jasonSerialize. This string format can be identified in JavaScript. From JavaScript if you need to load the real class from serialized format use the "eval()". It will be stored in a var. One dependency here is that after modification from JavaScript, you again need to serialize it, at this time from JavaScript. So you need to download a JS file named jason.js from "http://devpro.it/JSON/files/JSON-js.html". It has useful functions like "encode","decode" and many and you may again serialize the information and pass it to C# code side. From C# side use below code to deserialize the Employee object, which has modified from JavaScript.
Employee empd = ser.Deserialize<Employee>(jasonSerialize.ToString());
Now your "emd" contains the latest Employee object which is deserialized using JavaScriptSerializer class.
COMMENT USING