MVC 母版页动态数据
我有一个母版页需要显示数据库中的一些数据。例如,我在页面中有一个标题,它将显示用户拥有的消息/警报的数量。每个控制器都需要将此数据传递给视图。在 MVC 应用程序中执行此操作的最佳方法是什么?我显然不想在每个控制器操作中复制代码。
I have a master page that needs to display some data from my database. As an example, I have a header in the page that will display the number of messages / alerts that a user has. Every single controller is going to need to pass this data to the View. What is the best way to do this in an MVC application. I obviously don't want to copy the code in every controller action.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用子动作。 Phil Haack 在这篇博客文章。这样,您将拥有一个特定的控制器,用于从存储库中获取数据并将其传递到其自己的部分视图。然后在您的母版页中,您只需包含该操作:
这样其他控制器就不需要将数据传递到视图。它有一个完全独立的生命周期。
You could use child actions. Phil Haack does a great job explaining them in this blog post. This way you would have a specific controller for fetching the data from the repository and passing it to its own partial view. Then in your master page you would simply include the action:
This way other controllers don't need to pass the data to the view. It has a completely separate lifecycle.
Darin 答案的另一种选择是 ActionFilterAttribute,它将数据插入每个 Action 的 ViewData 中。该属性的放置位置定义了哪些操作可以获取该属性。将其放置在根 Controller 类中意味着所有操作都会获取它。
An alternative to Darin's answer is an
ActionFilterAttribute
, that plunks the data into every Action's ViewData. Where you place the attribute defines which actions get this. Placing it at a root Controller class means all actions will get it.您可以拥有一个所有模型都继承自的模型:
然后您可以拥有某种模型工厂来创建请求的模型:
因此,您可以将 IModelFactory 注入控制器中,然后在操作中使用它:
然后您的主人有
MasterModel
模型类型,然后可以使用此信息。这样,您的所有逻辑都可以保存在服务/存储库中,该服务/存储库被注入到创建每个视图模型的工厂中。这就是我所做的,效果很好。You could have a model that all models inherit from:
And then you could have some sort of model factory that will create the requested model:
So then you'd inject IModelFactory into your controller and then use it inside the action:
Then your master has
MasterModel
model type and then can use this information. This way all your logic could be kept inside a service/repository that is injected into the factory that creates each view's model. This is what I do and it works out great.