Detecting AJAX Requests in MonoRail

MonoRail ships with built-in support for the Prototype javascript framework.  The AjaxHelper providers wrappers for generating the required Prototype code to perform asynchronous requests.  Often times you will want to perform slightly different logic in your controller if the current request is an AJAX request (render a different view, cancel the layout, return some JSON serialized data, etc.).  You can use the following method for a consistent way of determining if the current request is an AJAX request:

namespace My.App
{
  using System;
  using Castle.MonoRail.Framework;

  public class ControllerBase : Controller
  {
    protected virtual bool IsAjaxRequest
    {
      get
      {
        string requestedWith = Request.Headers["X-Requested-With"];
        if( string.IsNullOrEmpty(requestedWith) )
          return false;

        return requestedWith.Equals("XMLHttpRequest", StringComparison.InvariantCultureIgnoreCase);
      }
    }
  }
}

This technique will also work for AJAX requests made using the jQuery framework.  More on jQuery later.

posted @ Saturday, November 17, 2007 6:23 AM


Print

Comments on this entry:

# Re: Detecting AJAX Requests in MonoRail

Left by nichols.mike.s AT gmail.com (Mike Nichols) at 11/17/2007 2:28 PM

I put this in a before.filter so that actions that are being called out of band have the layout, etc. stripped without me having to check for the request header.

# Link Listing - November 17, 2007

Left by Christopher Steen at 11/17/2007 11:42 PM

ASP.NET Detecting AJAX Requests in MonoRail [Via: Bill Pierce ] ASP.Net MVC Framework - Create your...

# Link Listing - November 17, 2007

Left by Christopher Steen at 11/17/2007 11:43 PM

Link Listing - November 17, 2007

Your comment:



 (will not be displayed)


 
 
 
Please add 1 and 6 and type the answer here:
 

Live Comment Preview:

 
«July»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678