Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net-mvc

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?

like image 623
Mathias F Avatar asked Jun 08 '09 14:06

Mathias F


People also ask

Which method is used to pass data from controller to view?

By using ViewBag, we can pass the data from Controller to View.

How pass data from view to controller in MVC?

You can do it with ViewModels like how you passed data from your controller to view. and in your HttpPost action, use a parameter with same name as the textbox name. If you want to post to another controller, you may use this overload of the BeginForm method.

Which of the following is a type of view in MVC?

On basis of data transfer mechanism ASP.NET MVC views are categorized as two types, Dynamic view. Strongly typed view.


3 Answers

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

like image 130
eu-ge-ne Avatar answered Oct 05 '22 03:10

eu-ge-ne


You can user this also in OnActionExecuting:

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

Hope this helps

like image 27
Jeison Souza Avatar answered Oct 05 '22 02:10

Jeison Souza


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

var model = filterContext.ActionParameters["model"] as CustomerModel;
like image 25
David Avatar answered Oct 05 '22 03:10

David