Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to maintain IsAjaxRequest() across RedirectToAction?

If you don't want any context or an example of why I need this, then skip to The question(s) at the bottom!

In a bid to keep things tidy I initially built my application without JavaScript. I am now attempting to add a layer of unobtrusive JavaScript on the top of it.

In the spirit of MVC I took advantage of the easy routing and re-routing you can do with things like RedirectToAction().

Suppose I have the following URL to kick off the sign up process:

http://www.mysite.com/signup

And suppose the sign up process is two steps long:

http://www.mysite.com/signup/1
http://www.mysite.com/signup/2

And suppose I want, if JavaScript is enabled, the sign up form to appear in a dialog box like ThickBox.

If the user leaves the sign up process at step 2, but later clicks the "sign up" button, I want this URL:

http://www.mysite.com/signup

To perform some business logic, checking the session. If they left a previous sign up effort half way through then I want to prompt them to resume that or start over.

I might end up with the following methods:

public ActionResult SignUp(int? step)
{
    if(!step.HasValue)
    {
        if((bool)Session["SignUpInProgress"] == true)
        {
            return RedirectToAction("WouldYouLikeToResume");
        }
        else
        {
            step = 1;
        }
    }
    ...
}

public ActionResult WouldYouLikeToResume()
{
    if(Request.IsAjaxRequest())
    {
        return View("WouldYouLikeToResumeControl");
    }
    return View();
}

The logic in WouldYouLikeToResume being:

  • If it's an AJAX request, only return the user control, or "partial", so that the modal popup box does not contain the master page.
  • Otherwise return the normal view

This fails, however, because once I redirect out of SignUp, IsAjaxRequest() becomes false.

Obviously there are very easy ways to fix this particular redirect, but I'd like to maintain the knowledge of the Ajax request globally to resolve this issue across my site.

The question(s):

ASP.NET MVC is very, very extensible.

Is it possible to intercept calls to RedirectToAction and inject something like "isAjaxRequest" in the parameters?

OR

Is there some other way I can detect, safely, that the originating call was an AJAX one?

OR

Am I going about this the completely wrong way?

like image 463
joshcomley Avatar asked Aug 18 '09 14:08

joshcomley


1 Answers

As requested by @joshcomley, an automated answer using the TempData approach:

This assumes that you have a BaseController and your controllers are inheriting from it.

public class AjaxianController : /*Base?*/Controller
{
    private const string AjaxTempKey = "__isAjax";


    public bool IsAjax
    {
        get { return Request.IsAjaxRequest() || (TempData.ContainsKey(AjaxTempKey)); }
    }


    protected override RedirectResult Redirect(string url)
    {
        ensureAjaxFlag();
        return base.Redirect(url);
    }

    protected override RedirectToRouteResult RedirectToAction(string actionName, string controllerName, System.Web.Routing.RouteValueDictionary routeValues)
    {
        ensureAjaxFlag();
        return base.RedirectToAction(actionName, controllerName, routeValues);
    }

    protected override RedirectToRouteResult RedirectToRoute(string routeName, System.Web.Routing.RouteValueDictionary routeValues)
    {
        ensureAjaxFlag();
        return base.RedirectToRoute(routeName, routeValues);
    }


    private void ensureAjaxFlag()
    {
        if (IsAjax)
            TempData[AjaxTempKey] = true;

        else if (TempData.ContainsKey(AjaxTempKey))
            TempData.Remove(AjaxTempKey);
    }
}

To use this, make your controller inherit from AjaxianController and use the "IsAjax" property instead of the IsAjaxRequest extension method, then all redirects on the controller will automatically maintain the ajax-or-not flag.

...

Havn't tested it though, so be wary of bugs :-)

...

Another generic approach that doesn't require using state that I can think of may requires you to modify your routes.

Specifically, you need to be able to add a generic word into your route, i.e.

{controller}/{action}/{format}.{ajax}.html

And then instead of checking for TempData, you'd check for RouteData["ajax"] instead.

And on the extension points, instead of setting the TempData key, you add "ajax" to your RouteData instead.

See this question on multiple format route for more info.

like image 100
chakrit Avatar answered Sep 24 '22 20:09

chakrit