Search code examples
c#asp.net-mvcasp.net-mvc-4viewdata

Create a base view model, but can't seem to hook into it in OnActionExecuting


I create a baseviewmodel that my other strongly typed view models inherit from.

BaseController:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
            var baseViewModel = ViewData.Model as BaseViewModel;
            if (baseViewModel != null)
            {
                // set common properties that I want to use in all views
            }
}

Now when I set a breakpoint on the if cluase, it seems baseViewModel is always null.

How do I set the base ViewData.Model to be of BaseViewModel?


Solution

  • OnActionExecuting is too early to look at the model.

    Called before the action method is invoked.

    You can see model in OnActionExecuted.