views:

171

answers:

1

Hi!

I'm trying to return a different view if a condition is met. I want to preserve the Model passed into the view from the action.

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var subAction = filterContext.RequestContext.RouteData.Values["subaction"].ToString();
        var action = filterContext.RequestContext.RouteData.Values["action"].ToString();

        if (!string.IsNullOrEmpty(subAction))
        {
            var view = (ViewResultBase) (filterContext.Result);
            filterContext.Result = View(action + subAction, view.ViewData.Model);
        }

        base.OnActionExecuting(filterContext);
    }

When doing it this way I get an "Object reference not set to an instance of an object.". Obviously, the Model haven't been set?

The reason I'm doing it this way, is that I want to keep the naming of the view as simple as possible. And my URL looks like this: /Global/Modules/Admin/Users/Create. That would return the view "UsersCreate". Which works. But the Model is either empty or null!

UPDATE

Actually. It just hit me. The behaviour is correct. Because I'm only returning a View. The action is never executed. The Users-action gets executed, but returns the view UsersCreate. How can I do a RedirectToAction kinda thing, without actually redirect.

+1  A: 

OnActionExecuting is run before the action so no model exists yet. You may try with OnActionExecuted which is called once the action returns an ActionResult.

Darin Dimitrov
But then it's too late to change the View. I get an `The model item passed into the dictionary is of type[..]`. The data passed is a list of users. I'm passing a viewmodel class `UsersCreate`. The list of users is the Model of the `Users` view.
Kordonme
Actually. It just hit me. The behaviour is correct. Because I'm only returning a View. The Action is never executed. The `Users` action gets executed, but returns the view `UsersCreate`. How can I do a `RedirectToAction` kinda thing, without actually redirect.
Kordonme