Thursday, September 5, 2013

ASP.NET - Pass objects between server and client- using http handler, Ajax and JSON

This article shows an example of how to pass objects from client to server and from server to client. This helps to maintain state of object between server and client. Make sure you do not store sensitive data on client side.

1) Create a web application

2) Define a class in C#
   public class MyData
        public int Prop1 { get; set; }
        public int Prop2 { get; set; }
        public int Result { get; set; }

3) Create a web form and define Javascript class which matches C# class

MyData = function (prop1, prop2) {
            this.Prop1 = prop1,
            this.Prop2 = prop2
            this.Result = 0;

4) Create request handler to handle Ajax requests

  public void ProcessRequest(HttpContext context)
            string action = context.Request.QueryString["action"];
            string input;
            using (StreamReader sr = new StreamReader(context.Request.InputStream))
                input = sr.ReadToEnd();

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            //Get object from client
            MyData data =(MyData)serializer.Deserialize(input,typeof(MyData));
            if (action == "add")
                data.Result = data.Prop1 + data.Prop2;
            context.Response.ContentType = "text/json";
            //Send object back to client

        public bool IsReusable
            get { return true; }

5) Call the server http handler from web form. Given below is the full javascript

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
        MyData = function (prop1, prop2) {
            this.Prop1 = prop1,
            this.Prop2 = prop2
            this.Result = 0;
        var myobject = new MyData(100, 2);

        $.ajax({ url: "RequestHandler.aspx?action=add",
            data: JSON.stringify(myobject),//Send object to server
            type: "POST",
            success: function (data) {//Get object from server


6) Register http handler using web.config

      <add verb="GET,POST" path="RequestHandler.aspx" type="HttpHandlerTest.RequestHandler"/>
    <compilation debug="true"/>

If you are running IIS7 you may have to register the handler as given below

 <handlers>   <add name="ajaxHandler" verb="GET,POST" path="RequestHandler.aspx" type="HttpHandlerTest.RequestHandler"/>

Run the application and you can see object values being set in client side and passed to server. After server sets “Result” in object it is passed back to client.  

No comments: