AJAX in ASP.NET using only HttpHandlers and Javascript

Today, almost every major site includes at least bits of AJAX calls, whenever to display a shopping cart, to dynamically load fragments of a page, or to pre-fetch the next images in a slideshow. jQuery, mootools, prototype... there is an increasing number of Javascript frameworks that, among other things, allow asynchronous calls to fetch data.

In .NET, although they are starting to migrate to jQuery (as we can see in ASP.NET MVC), by default when you create a .NET 3.5 website it references the not bad but clumbersome ASP.NET AJAX framework. Although I don't have anything against this practice, sometimes we don't need so much, or we might prefer to do things "our way" and for example communicate with the client site using JSON.

So this post is going to be like a small 3 steps tutorial on how to do 100% handcrafted basic AJAX requests using ASP.NET. Then you can so many things to it to make as good as you want.

Step 1: Build a HttpHandler

The most efficient way to develop AJAX call handlers in the server side is to use HttpHandlers. We keep the request context, but we skip all ASP.NET forms additional layers, providing a fast code in exchange of requiring a full implementation and management of the output by us.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. namespace Handlers
  5. {
  6. public class AJAXHandler : IHttpHandler
  7. {
  8. public bool IsReusable
  9. {
  10. get
  11. {
  12. return true;
  13. }
  14. }
  15. public void ProcessRequest(HttpContext context)
  16. {
  17. context.Response.Write("Received " + context.Request.RawUrl + " @ " + DateTime.Now.ToLongTimeString());
  18. }
  19. }
  20. }

Code is quite easy, so just remember to add a reference to System.Web to be able to implement IHttpHandler interface. IsReusable in this case is interesting as we can probably be having lots of requests to the handler.

Step 2: Plug the handler in a web project

We will create the website in the third step but doesn't matters as we just need to add a reference to the handler we've just created, and then edit the web.config to add it, under the <configuration> <system.web> node:

  1. <httpHandlers>
  2. <add verb="*" path="*.ajax" type="Handlers.AJAXHandler, Handlers"/>
  3. </httpHandlers>

We're configuring our site to enroute all calls that end in .ajax to our handler.

Step 3: Client side coding

Finally, we get to the important part: Making async calls from our webpages. The following example is for one page, of course to reuse it you should place all the <script> code inside a .js file and reference it.

We're using asynchronous responses using a callback function to not block anything, but yet this is a simple and standard code without advanced checks, no request manager engine, no error handling...

  1. <div>
  2. <div id="test_placeholder"></div>
  3. <input type="button" value="Test" onclick="javascript:AJAXCall('test.ajax', 'test_placeholder');" />
  4. </div>
  5. <script type="text/javascript">
  6. var xmlhttpReq;
  7. var targetElement;
  8. function AJAXCall(Url, Target)
  9. {
  10. targetElement = Target;
  11. if (window.XMLHttpRequest)
  12. {
  13. xmlhttpReq = new XMLHttpRequest();
  14. }
  15. else
  16. { // code for IE5-6
  17. xmlhttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  18. }
  19. xmlhttpReq.onreadystatechange = ajax_response;
  20. xmlhttpReq.open("GET", Url, true);
  21. xmlhttpReq.send(null);
  22. }
  23. function ajax_response()
  24. {
  25. // 4 completed, 3 in progress
  26. if (xmlhttpReq.readyState == 4 && xmlhttpReq.status == 200)
  27. {
  28. if (xmlhttpReq.responseText)
  29. {
  30. // responseText contains output
  31. document.getElementById(targetElement).innerHTML = xmlhttpReq.responseText;
  32. }
  33. else
  34. {
  35. document.getElementById(targetElement).innerHTML = '';
  36. }
  37. }
  38. }
  39. </script>

Each time we click on the button we'll see a timestamped response.

From here, you can improve the handler (or add more) to handle JSON, XML, even HTML templates, the limit is your imagination ;)

Tags: Development

AJAX in ASP.NET using only HttpHandlers and Javascript published @ . Author: