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.
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.
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