views:

72

answers:

1

Is there a way to inject the referrer action from an action filter? Lets say I have a view that comes from action X. In dies view I call action Y and I want to redirect again to action X. (There are multiple X actions that call action Y). I thought that it could be nice if I had a parameter call referrerAction and an action filter that filled it with the previous action. Is it possible?

Thanks.

+1  A: 

Here's how I do:

  public class ReturnPointAttribute : Attribute
  {
  }

  public class BaseController: Controller
  {
      private string returnPointUrl = null;
      protected override void OnActionExecuted(ActionExecutedContext filterContext)
      {
         base.OnActionExecuted(filterContext);
         if (filterContext.ActionDescriptor.IsDefined(typeof(ReturnPointAttribute), true))
            returnPointUrl = filterContext.HttpContext.Request.Url.ToString();
      }
      public ActionResult RedirectOrReturn<T>(Expression<Action<T>> action) where T : BaseController
      {
         return returnPointUrl.IsNullOrEmpty() 
            ? MyControllerExtensions.RedirectToAction(this, action) 
            : (ActionResult)Redirect(returnPointUrl);
      }
   }

Now, you mark you X actions with [ReturnPoint] and call RedirectOrReturn() if you want to return back.

I do not use UrlReferrer because it can be wrong and I have no control over its value. With ReturnPoint, you can also have groups, e.g. [ReturnPoint("Orders")] and RedirectOrReturn("Orders").

Of course, you can have more automatic behaviour in OnActionExecuted - e.g. it can check if returned result is Redirect, and automatically go to ReturnPoint if it has value. Or you can control this with [ReturnPoint(Automatic=true)], and so on.

queen3
Shouldn't he mark Y action with [ReturnPoint] attribute?
Misha N.
No, he wants to redirect back to X, so that's the return point. For example, cart is the return point, it will call misc actions but they will want to return back to the cart - so we mark Cart/Index as [ReturnPoint]. Then, Edit() will call RedirectOrReturn().
queen3