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?
By using ViewBag, we can pass the data from Controller to View.
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.
On basis of data transfer mechanism ASP.NET MVC views are categorized as two types, Dynamic view. Strongly typed view.
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
You can user this also in OnActionExecuting:
BaseModel model = filterContext.ActionParameters.SingleOrDefault(m => m.Value is BaseModel).Value as BaseModel;
Hope this helps
This is an old question but now I am able to access the model during OnActionExecuting:
var model = filterContext.ActionParameters["model"] as CustomerModel;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With