Mathias F
Mathias F

Reputation: 15901

How to set model data in ActionFilterAttribute when using a typed view

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 safer way to acces the Model?

Upvotes: 7

Views: 4446

Answers (3)

David
David

Reputation: 1570

This is an old question but now I am able to access the model during OnActionExecuting:

var model = filterContext.ActionParameters["model"] as CustomerModel;

Upvotes: 1

Jeison Souza
Jeison Souza

Reputation: 434

You can user this also in OnActionExecuting:

BaseModel model = filterContext.ActionParameters.SingleOrDefault(m => m.Value is BaseModel).Value as BaseModel;

Hope this helps

Upvotes: 4

eu-ge-ne
eu-ge-ne

Reputation: 28153

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

Upvotes: 14

Related Questions