Web Developer, Software Engineer and Mixed Language Artist
RSS icon Email icon Home icon
  • Replacing Request.IsAjaxRequest() with ActionFilter

    Posted on December 8th, 2010 Jamie No comments

    Ever wondered if you can replace all those

    ?View Code CSHARP
    if(Request.IsAjaxRequest())
    {
    // return some partial view
    }

    with an action filter?

    Although it’s not much code to write the above in many controller methods, I was intrigued to figure out how this behaviour could be replaced through the use of a custom ActionFilter. Here’s what I came up with (It might not be any better than using the above and this was created purely out of a desire to figure out how possible it could be):

    Action Filter:

    ?View Code CSHARP
     public class ReturnPartialForAjaxRequestActionFilter : ActionFilterAttribute
        {
            public string ViewName { get; set; }
     
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                if (ViewName != null)
                {
                    var request = filterContext.RequestContext.HttpContext.Request;
                    if (request.IsAjaxRequest())
                    {
                        var result = (ViewResult)filterContext.Result;
     
                        filterContext.Result = new PartialViewResult
                        {
                            ViewName = ViewName,
                            ViewData = result.ViewData
                        };
                    }
                }
                base.OnActionExecuted(filterContext);
            }
        }

    Usage:

    ?View Code CSHARP
    [ReturnPartialForAjaxRequestActionFilter(ViewName = "PartialViewName")]
    public ActionResult MyActionResult()
    {
    }

    This is possibly a bit overkill given that it most likely involves more typing than simply writing out the original if statement however as a thought exercise it was quite fun to implement.

    MVC

    Leave a reply