ASP.NET MVC在所有子视图3布局ViewBag数据 [英] ASP.NET MVC 3 layout ViewBag data across all child views

查看:142
本文介绍了ASP.NET MVC在所有子视图3布局ViewBag数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要传递给我们的布局文件,不管是什么子视图是动态的数据。例如,我们在布局的标题显示一些用户专用数据。

We need dynamic data passed to our layout file, no matter what the child view is. For example, we display some user specific data in the header of the layout.

我们如何可以通过这个数据到布局视图,而无需单独提供它的每个动作?如果我们使用自定义的控制器,或者是有一个更好的解决方案?

How can we pass this data to the layout view without each action having to supply it independently? Should we use a custom controller, or is there a better solution?

推荐答案

这是我使用的是有一个基本视图模型,从我的所有视图模型得出的策略。我使用的是主控制器,虽然你也可以使用一个全球性的过滤器,并覆盖OnActionExecuted。当我发现它返回一个ViewResult一个动作,我投的模式,我基本视图模式和设置共同的属性上从主控制器的型号。

The strategy that I use is to have a base view model from which all of my view models derive. I use a base controller, though you could also use a global filter, and override OnActionExecuted. When I detect an action that returns a ViewResult, I cast the model to my base view model and set the common properties on the model from the base controller.

的全局过滤器和一个主控制器之间的选择取决于多种因素。如果真的适用于所有操作(即返回查看结果),你并不需要注射才能访问某些资源,那么我可能会去的过滤器。如果你需要有相关性注入,或者你有一些控制器,其中数据将被用于和其他人哪里会不会(比如管理员控制器),那么我会去的基本控制器的路线。你需要记住从控制器,如果你去用它来推导。

The choice between a global filter and a base controller depends on a variety of factors. If it really applies to all actions (that return view results) and you don't need injection to get access to some resources, then I'd probably go with the filter. If you need to have dependencies injected or you have some controllers where the data would be applied and others where it wouldn't (say the Admin controller), then I'd go the base controller route. You will need to remember to derive from the controller if you go with it.

您也可以做的ViewBag同样的事情,如果你不希望从一个共同的视图模型来推导。我喜欢有强类型的模式,但情况因人而异。

You could also do the same thing with the ViewBag if you don't want to derive from a common view model. I like having the strongly-typed model, but YMMV.

这篇关于ASP.NET MVC在所有子视图3布局ViewBag数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆