As javascript libraries, particularly jQuery, increase in popularity so do web techniques using AJAX and JSON.
Have you ever seen this code? It is front and back of an ASPX file with the single responsibility to return JSON data per an AJAX request.
GetDataPage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetDataPage.aspx.cs" Inherits="GetDataPage" %> <%-- This minimal code is here to prevent the following error: "Using themed css files requires a header control on the page" Please see http://www.west-wind.com/WebLog/posts/4662.aspx for more information --%> <head id="Head1" runat="server" visible="false" />
GetDataPage.aspx.cs
using System; using System.Web; using System.Text; public partial class GetDataPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Clear out the buffer Response.ClearHeaders(); Response.ClearContent(); Response.Clear(); // Do not cache response Response.Cache.SetCacheability(HttpCacheability.NoCache); // Set the content type and encoding for JSON Response.ContentType = "application/json"; Response.ContentEncoding = Encoding.UTF8; int page = int.Parse(Request["p"]); string results = DataAccess.GetResults(page); Response.Write(results); // Flush the response buffer Response.Flush(); // Complete the request. NOTE: Do not use Response.End() here, // because it throws a ThreadAbortException, which cannot be caught! HttpContext.Current.ApplicationInstance.CompleteRequest(); } }
You may have noticed there’s a comment for nearly every code block. At first, one may find the comments redundant and unnecessary, but really they are call for help. A code:comment ratio like this usually indicates you really need to focus on what’s happening with the code because if you aren’t paying attention, bad things might happen.
As you have undoubtedly concluded, there’s a lot of overhead associated with returning JSON data from an ASPX file. This statement is especially true if you consider the alternative, an HTTPHandler. Here’s a cleaner, best-practices approach which provides the same outcome with less code, comments and risk.
GetDataHandler.ashx
<%@ WebHandler Language="C#" Class="GetDataHandler" %> using System.Text; using System.Web; public class GetDataHandler : IHttpHandler { public bool IsReusable { get { return false; } } public void ProcessRequest (HttpContext context) { context.Response.ContentType = "application/json"; context.Response.ContentEncoding = Encoding.UTF8; int page = int.Parse(context.Request["p"]); string results = DataAccess.GetResults(page); context.Response.Write(results); } }
If you are already accustomed to using generic handlers to stream back images, XML, JSON data, etc, this post was probably a bore. But it’s sometimes easy to forget what’s available to
you in the vast .NET stack, so hopefully you appreciate the friendly reminder. In either case, it still surprises me how many examples use the ASPX approach. In fact, the practice is common enough that I sometimes wonder if there’s an HTTPHandler gotcha to which I’m not privy . If I am missing something, please let me know.
If you’re still interested, attached you’ll find code which populates two jQuery Flexbox controls using JSON data provided through an ASPX and ASHX files. This may be worthwhile download if you’re interest in the generic handler code or you want a further look at Flexbox in action after last week’s post.
December 16th, 2008 at 12:06 pm
Any chance for a link to the code?
December 16th, 2008 at 12:20 pm
Oops. It’s there now. Thanks.
March 24th, 2009 at 5:56 am
nice post! simple and easy to understand..
March 24th, 2009 at 7:34 am
@Jeff Many thanks.
June 15th, 2009 at 12:35 am
Thanks for the post.
At least there’s one other person is also using the generic handler for ajax requests. I thought I’m the only one.
I too haven’t picked up any gotchas yet.
It would be nice though if we had a method of converting IQuerable to Json like in mvc
June 15th, 2009 at 7:10 am
@Paul Allies - Thanks for the comments. I’m surprised, too, that few seem to use the generic handler — in examples anyway. IQueryable to Json, eh? I’ll stay on the lookout. Thanks.
September 29th, 2009 at 6:13 pm
Ben,
Is there a benefit of using generic handlers to return JSON instead of using a Webservice with the ScriptService Attribute?
I’m able to return an array of any object type to a jTemplate. It seems compiling a string of the JSON is opening up more possibilities for typos.
That being said, I am fairly new to using jQuery, so I’m probably overlooking some plain explanation.
September 29th, 2009 at 7:08 pm
Hi Mike. That’s a great question. I think my sample project may not have represented JSON very well. In most cases, one would simply serialize an object(s) to JSON rather than jumping through hoops building the string like I did in the sample. As long as your objects are serializable, I’m not sure there’s much concern with typos. Of course, your solution is one I hadn’t actually considered and should work perfectly well. I’m really glad to provided an alternative approach. Many thanks.