tags:

views:

187

answers:

1

I use strongly typed views where all ViewModels inherit a class BaseViewModel.

In an ActionFilter that decorates all Controllers I want to use the Model.

Right now I can only access it like this:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ViewModelBase model = (ViewModelBase)filterContext.ActionParameters["viewModel"];
        base.OnActionExecuting(filterContext);
   }

The problem is, that I have to know the key "viewModel". The key is viewModel, because in my controller I used:

return View("MyView", viewModel)

Is there a saver way to acces the Model?

+3  A: 

OnActionExecuting works just before your Action is executed - thus the Model is set to null. You could access your ViewData (or ViewData.Model) in OnActionExecuted:

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    var model = filterContext.Controller.ViewData.Model as YourModel;

    ...
}

Hope this helps

eu-ge-ne
This makes sense. Part of my filter can access values from route and need to be known before the Action executes. I still have this part in OnActionExecuting. The rest is now in OnActionExecuted.
Malcolm Frexner