在 asp.net-mvc 中,使用 Base ViewModel 在 Site.Master 页面上显示动态内容的最佳方式是什么
我有一个 asp.net-mvc 站点,并且有一些我想在每个页面上显示的信息。我创建了一个名为 BaseViewModel 的类,每个 viewModel 类都继承自 BaseViewModel。 Site.Master 视图直接绑定到 BaseViewModel。
现在,基类有一个名为 MenuLinks 的属性。
menulinks 属性从数据库调用中填充,因此在实例化 ViewModel 的每个控制器操作上,我添加了一个新行:
viewModel.MenuLinks = _repository.GetMenuLinks();
我有很多控制器、操作和视图模型。有没有更干净的方法可以完成上述操作,而不必将此行放在每个控制器操作上方。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以编写一个自定义操作过滤器属性,其中将在每个操作之后执行并设置基本模型的属性:
现在剩下的就是用这个操作过滤器来装饰您的基本控制器。
处理此问题的另一种方法是使用 子操作 和没有基本视图模型。
You could write a custom action filter attribute which will execute after each action and set the property of the base model:
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.
在你的 site.master 页面中,
如果你愿意的话,你可以在你的 homecontroller 中调用一个动作,让它返回 html 的部分视图,在你的情况下是一些菜单链接。
您可以创建部分“MenuPartial.ascx”
in your site.master page, call
you can call an action in your homecontroller if you want and just have it return a partial view of the html, in your case some menu links.
you can create a partial "MenuPartial.ascx"
我喜欢 justins 示例,因为它使用 MVC 方法。我修改了它,使其适用于带剃刀的 MVC3。
这是我的 _Layout.cshtml 中的内容:
我创建了一个 LayoutController,它具有如下菜单操作:
它呈现部分视图名称 Menu.cshtml
I like justins example because it uses a MVC approach. I modified it so it works for MVC3 with razor.
Here's what I have in my _Layout.cshtml:
I created a LayoutController that has a menu action like this:
Which renders a partial view name Menu.cshtml
我认为在不修改所有控制器操作的情况下实现结果的最佳方法是创建一个自定义操作过滤器,用菜单链接填充 BaseModel 的属性。
然后您可以拥有一个 BaseController 类并将属性添加到 BaseController 中。
I think the best way to achieve your result without modifying all your controller action is to create a custom action filter that populate a property of your BaseModel with your menu links.
Then you could have a BaseController class and add the attribute to the BaseController.
创建一个工厂类,为您提供已配置的视图模型。
然后在你的控制器中你可以使用 Factory 类而不是直接创建 viewModel 的实例
Create a factory class that give you the viewmodel already configured.
then in your controller you can use the Factory class instead of directly create an instance of viewModel