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
            context.Response.Write(serializer.Serialize(data));

        }
        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>
    <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
                alert(data.Result);
            }
        });

    </script>

6) Register http handler using web.config

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

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


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


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.  

ASP.NET – Http handlers and AJAX

Given below is an example of implementing AJAX in asp.net using http handlers. Custom http handler with AJAX allows developers to add lot of features to classic ASP.NET application without postbacks. I personally find this way of development better than the MVC model.

Let’s implement an example. I used VS 2010 and .net 4.0
------------------------------------------------

1) Create a new web application – HttpHandlerTest

2) Create a new class file –‘RequestHandler’ . Make sure that the class implements “IHttpHandler”

    public class RequestHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request.QueryString["action"];
            string input;
            using (StreamReader sr = new StreamReader(context.Request.InputStream))
            {
                input = sr.ReadToEnd();
            }
            int result = 0;
            if (action == "add")
            {
                result = Int32.Parse(input.Split(new char[] { ',' })[0]) + Int32.Parse(input.Split(new char[] { ',' })[1]);
            }
            context.Response.ContentType = "text/json";
            context.Response.Write(result.ToString());
        }
        public bool IsReusable
        {
            get { return true; }
        }
    }


3) Create an aspx page to call the handler. Enter below JS to the page. Make sure that you have reference to jQuery

  <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script>
        $.ajax({ url: "RequestHandler.aspx?action=add",
            data: "10,11",
            type: "POST",
            success: function (data) {
                alert(data);
            }
        });

    </script>


4) Register handler in web.config
<system.web>
    <httpHandlers>
      <add verb="GET,POST" path="RequestHandler.aspx" type="HttpHandlerTest.RequestHandler"/>
    </httpHandlers>
    <compilation debug="true"/>
 </system.web>

If you are running IIS7 you may have to register the handler as given below
<system.webServer>
  <handlers>
    <add name="ajaxHandler" verb="GET,POST" path="RequestHandler.aspx" type="HttpHandlerTest.RequestHandler"/>
  </handlers>

</system.webServer>



That’s it. Now run the application and you can see the result from handler as a JS alert message.
 --------------------------------
Wasn't that easy. Let me know what you think.  Not just about this article, but also about the blog if you have read the other articles I posted.


Happy coding