1

I have an action filter that redirects to route when certain criteria is met.

 public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (someValue)
        {
            filterContext.Result = new RedirectToRouteResult("MyCustomRoute", new RouteValueDictionary());
        }

        base.OnActionExecuting(filterContext);
    }

and this is my custom route:

routes.MapRoute("MyCustomRoute",
            "customRoute/",
            new { controller = "Custom", action = "CustomAction" },
            new[] { "CustomControllerNamespace" });

This is triggered when a user navigates to a route for example: /someRoute?param1=1&param2=2&param3=3

When I debug the action filter I can see that inside filterContext.ActionParameters I have 2 models containing the parameters passed in the url.

This is my action:

 public ActionResult CustomAction(CustomModel model, CustomModel2 model2)
    {// do something}

This action has the same parameters as the original action.

The problem is that when I redirect to this action from the action filter the parameters in model and model 2 are null.

If I remove the original route from the RouteTable and create a route with the same name and url but with different controller, the action filter is triggered and when I redirect to the CustomAction the models are populated with the values.

Do you know how I can pass the ActionParameters when I redirect to another route? I don't want to pass them inside the RouteValueDictionary. Do you have any idea why this is happening?

EDIT:

After some tweaking I found that I can pass the parameters from the 2 models by manually passing each parameter to a RouteValueDictionary, that I use in RedirectToRouteResult.

var model = filterContext.ActionParameters["model"] as CustomModel;
            var model2= filterContext.ActionParameters["model2"] as CustomModel2;
            var routeValues = new RouteValueDictionary();

            if (model != null && model2!= null)
            {
                routeValues = new RouteValueDictionary(new
                {
                    Param1 = model.Param1,
                    Param2 = model.Param2,
                    Param3 = model2.Param3
                });
            }

filterContext.Result = new RedirectToRouteResult("MyCustomRoute", routeValues);

Is there any other way to do this? I don't think that this is a good practice and if a new property is added or changed I'll have to change this code.

Ivan Stoyanov
  • 5,412
  • 12
  • 55
  • 71

1 Answers1

-1

As far as I know, you can't pass ViewModels (complex objects) to methods such as RedirectToAction and RedirectToRoute.

There are various methods to overcome this, one of them being TempData as shown here.

Community
  • 1
  • 1
J86
  • 14,345
  • 47
  • 130
  • 228