Thursday, September 5, 2013

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 

No comments: