在asp.net MVC的,什么是有一个基本视图模型显示的Site.Master页上的动态内容的最佳方式 [英] in asp.net-mvc, what is the best way to have a Base ViewModel to show dynamic content on the Site.Master page
问题描述
我有一个asp.net MVC的网站,还有就是我想告诉每一页上的一些信息。我创建了一个名为BaseViewModel类,每个视图模型类的继承BaseViewModel。 Site.master母视图结合直接BaseViewModel。
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.
现在的基类有一个属性叫做MenuLinks。
Right now the base class has one property called MenuLinks.
该menulinks属性,都会从数据库调用填充等被instatiating一个ViewModel我增加了新的生产线每一个控制器动作:
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.
这篇关于在asp.net MVC的,什么是有一个基本视图模型显示的Site.Master页上的动态内容的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!