Frage

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?

War es hilfreich?

Lösung

OnActionExecuting is too early to look at the model.

Called before the action method is invoked.

You can see model in OnActionExecuted.

Andere Tipps

The ViewData is intended to send model from controller action to view.

Your OnActionExecuting hook is BEFORE the action method is invoked... so that is why you see the viewdata's model as null. Try using OnActionExecuted instead.

You can then check if the Model is of that base type using the keyword is this way:

if(ViewData.Model != null && ViewData.Model is BaseModel){

    var base = ViewData.Model as BaseModel;
    // set common properties
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top