Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to RedirectToAction from within an ActionFilterAttribute?

Tags:

asp.net-mvc

whats the best way to do a redirect (preferably a redirect to action) from within an ActionFilterAttribute?

I want to be able to pass data into the controller action from within the ActionFilterAttribute as well.

like image 249
Jon Erickson Avatar asked Dec 18 '09 18:12

Jon Erickson


People also ask

How do I redirect an action filter?

Alternatively to a redirect, if it is calling your own code, you could use this: actionContext. Result = new RedirectToRouteResult( new RouteValueDictionary(new { controller = "Home", action = "Error" }) ); actionContext. Result.

How do I redirect OnActionExecuting in base controller?

public override void OnActionExecuting(ActionExecutingContext filterContext) { ... if (needToRedirect) { ... filterContext. Result = new RedirectResult(url); return; } ... } Instead of new RedirectResult(url) you could also use new RedirectToAction(string action, string controller) .

Which is correct syntax for RedirectToAction?

RedirectToAction(String, String, RouteValueDictionary) Redirects to the specified action using the action name, controller name, and route values.

Can we pass model in RedirectToAction?

By including a NuGet package called MvcContrib you can easily pass model or form data through a simple RedirectToAction function call inside of your controllers.


1 Answers

To redirect, override OnActionExecuting and assign a new RedirectToRouteResult to filterContext.Result:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult( 
            new RouteValueDictionary { { "action", "newActionName" },
                                       { "actionArgument", someData } });
    }

To assign data when redirecting, put it into the route, as shown above.

like image 133
Craig Stuntz Avatar answered Oct 28 '22 08:10

Craig Stuntz