C#在集中MVC重复可视数据 [英] C# Centralizing repeating VIewData in MVC
问题描述
当用户登录到我的应用程序,我想显示在整个应用他的名字。我使用asp.net MVC框架。但我不希望是必须把每个控制器是这样的:
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"];
这是因为你可能不重复自己。 (我相信这是DRY [不要重复自己]面向对象编程的原理。)
该计算机[用户]是我的母版。所以我的问题是,什么是处理在一个地方,我的计算机[用户]一种巧妙的方法?
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?
推荐答案
您可以在任何一个控制器基类,或者应用到控制器/动作的动作过滤器做到这一点很容易。在这两种情况下,你会得到之前(或之后)的动作确实触及请求的机会 - 让你可以在那里添加此功能
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.
例如:
public class UserInfoAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(
ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
filterContext.Controller.ViewData["user"] = "Foo";
}
}
...
[HandleError, UserInfo]
public class HomeController : Controller
{...}
(也可以在使用的动作的(方法)级)
或一个共同的基类:
public abstract class ControllerBase : Controller
{
protected override void OnActionExecuting(
ActionExecutingContext filterContext)
{
ViewData["user"] = "Bar";
base.OnActionExecuting(filterContext);
}
}
[HandleError]
public class HomeController : ControllerBase
{...}
这篇关于C#在集中MVC重复可视数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!