C# 在 MVC 中集中重复的 VIewData
当用户登录我的应用程序时,我想在整个应用程序中显示他的名字。 我正在使用 asp.net MVC 框架。 但我不想要的是,必须在每个控制器中放入类似以下内容:
ViewData["User"] = Session["User"];
这是因为你可能不会重复自己。 (我相信这是 OO 编程的 DRY [不要重复自己] 原则。) ViewData["User"] 位于我的主页上。 所以我的问题是,在一个地方处理我的 ViewData["User"] 的一种巧妙方法是什么?
When a user log in into my application i want to show his name throughout the whole application. I am using the asp.net MVC framework. But what i don't want is that is have to put in every controller something like:
ViewData["User"] = Session["User"];
This because you may not repeat yourself. (I believe this is the DRY [Don't Repeat Yourself] principle of OO programming.)
The ViewData["User"] is on my masterpage. So my question is, what is a neat way to handle my ViewData["User"] on one place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在控制器基类或应用于控制器/操作的操作过滤器中相当轻松地完成此操作。 在任何一种情况下,您都有机会在操作之前(或之后)触摸请求 - 因此您可以在那里添加此功能。
例如:(
也可以在操作(方法)级别使用)
或与公共基类一起使用:
You can do this fairly easily in either a controller base-class, or an action-filter that is applied to the controllers/actions. In either case, you get the chance to touch the request before (or after) the action does - so you can add this functionality there.
For example:
(can also be used at the action (method) level)
or with a common base-class:
已经过去一年了,但我刚刚偶然发现了这个问题,我相信有更好的答案。
Jimmy Bogard 将接受的答案中描述的解决方案描述为反模式,并提供了涉及 RenderAction 的更好解决方案:http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/18/the-filter -viewdata-反模式.aspx
It's been a year, but I've just stumbled across this question and I believe there's a better answer.
Jimmy Bogard describes the solution described in the accepted answer as an anti-pattern and offers a better solution involving
RenderAction
: http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/18/the-filter-viewdata-anti-pattern.aspx在整个应用程序中提供持久模型数据的另一种方法是使用自定义控制器覆盖 DefaultFactoryController。 在您的 CustomerFactoryController 中,您可以将 ViewBag 与您想要保留的模型结合起来。
Another method for providing persistent model data through out your entire application is by overriding the DefaultFactoryController with your custom one. In your CustomerFactoryController, you would hydrate the ViewBag with the model you are wanting to persist.
使用 UserName 属性为您的模型创建一个基类:
为您的控制器创建一个基类并覆盖它的 OnActionExecuted 方法。 在其中检查模型是否从 BaseModel 派生,如果是,则设置它的 UserName 属性。
然后您将能够在视图中显示用户的用户名,如下所示:
另请参阅:
Create a base class for your models with UserName property:
Create a base class for you controllers and override it's OnActionExecuted method. Within it check if model is derrived from BaseModel and if so, set it's UserName property.
Then you will be able to display user's UserName in the view like this:
See also: