Monday, August 15, 2011

ASP.NET MVC - Identifying the nature of request using IsAjaxRequest()

HttpRequestBase class is provided with an extension method called IsAjaxRequest() which specifies whether the request has been initiated as an AJAX call/request. Actually it looks for a specific header (x-requested-with: XMLHttpRequest) in the HTTP request made and acts accordingly.

From the Controller class we can access this method using Request.IsAjaxRequest(), as the Request property holds/gets the HttpRequestBase object for the current HttpRequest.

Ok, now let us see the real use of this IsAjaxRequest() method. If you see the ProjectMemberDetailsController in my previous post ASP.NET MVC 3 and jQuery templates - Part2, I've used two methods ProjectMemberList() and ProjectMemberList(string experience) with [HttpPost] attribute. Each serves the following purpose: 
  1. ProjectMemberList() - Called when the view is rendered initially by the view engine. Here we need to return the related view and this is a non-AJAX call by nature.
  2. ProjectMemberList(string experience) [HttpPost] - Invoked whenever the AJAX call is initiated using POST request. Here we need to return the JSON result.
 With the help of IsAjaxRequest(), let us see how can we change the ProjectMemberDetailsController.

Snippet 1 (ProjectMemberDetailsController with IsAjaxRequest())

public class ProjectMemberDetailsController : Controller
    public ActionResult ProjectMemberList(string experience)
        SampleData sampleData = new SampleData();

        if (Request.IsAjaxRequest())
            if (string.IsNullOrEmpty(experience) || experience.Equals("All"))
                return Json(sampleData.ProjectMemberList, JsonRequestBehavior.AllowGet);
                return Json(sampleData.GetProjectMembersWithExpGreaterThan(int.Parse(experience)), JsonRequestBehavior.AllowGet);

        return View();

From the above snippet we can clearly infer that how effectively we can utilize the IsAjaxRequest() method. It'll be very much helpful and can be used effectively in lot of scenarios. One such scenario I faced is while customizing the Authorize attribute, in order to determine the authorization logic based on the nature of the request.


No comments:

Post a Comment

Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.