Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in asp.net-mvc, what is the best way to have a Base ViewModel to show dynamic content on the Site.Master page

i have an asp.net-mvc site and there is some information that i want to show on every page. I have created a class called BaseViewModel and each of the viewModel classes inherit from BaseViewModel. The Site.Master view binds to the BaseViewModel directly.

Right now the base class has one property called MenuLinks.

The menulinks property gets populated from a database call so on every controller action that is instatiating a ViewModel i am adding a new line:

 viewModel.MenuLinks = _repository.GetMenuLinks();

i have a lot of controllers, actions and view models. Is there any cleaner way i can do the above without having to put this line above on every single controller action.

like image 605
leora Avatar asked Jan 24 '26 00:01

leora


1 Answers

You could write a custom action filter attribute which will execute after each action and set the property of the base model:

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    base.OnActionExecuted(filterContext);
    var viewResult = filterContext.Result as ViewResultBase;
    if (viewResult != null) 
    {
        var model = viewResult.ViewData.Model as BaseViewModel;
        if (model != null)
        {
            model.MenuLinks = _repository.GetMenuLinks();
        }
    }
}

Now all that's left is to decorate your base controller with this action filter.

Another way to handle this is to use child actions and not have a base view model.

like image 127
Darin Dimitrov Avatar answered Jan 26 '26 18:01

Darin Dimitrov