Asp.net mvc - Accessing view Model from a custom Action filter
The model is at:
filterContext.Controller.ViewData.Model
I don't know why but filterContext.Controller.ViewData.Model
is always null even when the model bind is executed before OnActionExecuted
. I found a solution using the OnModelUpdated
event to set that property before.
I have the model binder:
public class CustomModelBinder: DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
controllerContext.Controller.ViewData.Model = bindingContext.Model;
base.OnModelUpdated(controllerContext, bindingContext);
}
}
After that you need to set the default binder to your new model binder in Application_Start()
section in Global.asax:
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
Finally you can access your Model
in an ActionFilterAttribute
:
public class TraceLog : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//filterContext.Controller.ViewData.Model now isn't null
base.OnActionExecuted(filterContext);
}
}