We’ve already seen how to perform an AJAX call using just a simple ASP.NET web page. Now we’ll see how to do it with an HTTP handler instead of a web page.

But, what is an HTTP handler? Well, as its names suggests, it is an element that handles HTTP requests. Well, but that’s what an .aspx web page does, right? Sure, but in a lengthier, slower and resource-hungrier way. Regular web pages inherit from the System.Web.UI.Page class, which contains a lot of overhead and pre and post-processing in order to make it easier for the programmer to return HTML code to the client performing a request. In other words, the web page class has stuff to make it easier to develop a web page. It’s got some logic, doesn’t it?

But, what if we don’t want to return a web page? Then we’re just wasting resources in our server, since we’re not to going to use any of the facilities the web page class provides. If what we want to return is not an actual web page, then you should avoid using the System.Web.UI.Page class.

We’ll take a closer look at HTTP handlers in some other post I’m preparing, but for now you should know that they’re more adequate for processing AJAX requests.

This example is quite similar to the previous one: the only difference is that the HTTP handler replaces the web page. Except for that, we’ll be doing the same call and using the same javascript code. However, just for clarity’s shake, I’ll be posting all the code involved here.

Ok, so now we’ll get our hands dirty and start doing some work! First, we’ll need some HTML code to draw a simple test page. Start a new Visual Studio Project and get to the newly created page. On the C# codebehind of the new page we won’t be changing anything. Leave everything by default. We’ll be doing our work in the .aspx part. This HTML code should be sufficient for our needs:

<body>
    <form id="form1" runat="server">
      <h2>jQuery AJAX call test page</h2>
      <button type="button" onclick='ExecuteAJAXCall()'>Get server time</button>
      <br /><br />
      <div id="DataContainer" ></div>
    </form>
</body>

This is a very simple page. We’ll just have a heading, a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now we need some actual code to make the AJAX call:

<script type="text/javascript">
   function ExecuteAJAXCall() {
         $.ajax({
             url: "AJAXRequest.ashx",
             dataType: 'json',
             success: Callback_AJAXCall
         });
   };

   function Callback_AJAXCall(data) {
         document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data;
   };
</script>

Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. We’re passing three parameters to the function: the URL of the element that will get called, they type of data we’re expecting back (JSON in this case) and the javascript function to execute once the data gets back to the client. The jQuery ajax function has many more parameters, but we didn’t need them this time since the example is not very complicated.

The function called when the data is returned is very simple: its only purpose is to take the string returned from the server and write it in the container we previously created for this purpose. Note that the parameter it receives, data, is already a javascript object. The AJAX call returns a simple string from the server, but the jQuery function is smart enough to convert that string to a javascript object and pass it to the function we indicated.

Ok, now we’re getting to the interesting point. Now that we have the test page in place, let’s deal with the AJAX call server-side. The AJAXRequest.ashx HTTP handler is the link between the client web browser and the server. Here we’ll process everything we need and we’ll return a string to the client with the data requested.

So here’s how we program an HTTP handler:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    ///
    /// Processes AJAX requests
    ///
    public class AJAXRequest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
            string CurrentDate = DateTime.Now.ToString();

            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";
            context.Response.Write(JSSerializer.Serialize(CurrentDate));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

To implement an HTTP handler you just need to implement the System.Web.IHttpHandler interface. You need to provide the desired behaviour to the ProcessRequest method and the  IsReusable property. The first method is the one which actually takes care of processing the HTTP requests and returning the data. The IsReusable property determines whether this instance of HTTP handler can be reused for fulfilling another request of the same type.

This implementation is very simple: it just takes the current date and time from the server, converts it to JSON format and returns it. Note the System.Web.Script.Serialization class we’re importing. This class takes care of converting the object we want to return to JSON format. Note the line in which we deactivate the cache as well. If you don’t do this, the AJAX call will always seem to return the same data, as the web browser will have kept a copy of it the first time it was executed. Most AJAX calls need the cache disabled in order to work properly.

You can download a copy of the Visual Studio project and do some tests to check how it works:

jQueryAJAXHTTPHandlerCall.zip

Related posts:

  1. AJAX call using an ASP.NET web page
  2. AJAX call using an ASP.NET Page Method
  3. AJAX call using ASP.NET Web Services
  4. Different ways to use AJAX in ASP.NET
  5. HTML 5 C# Web Sockets server and ASP.NET client implementation