本文介绍了在所有视图上访问Viewbag属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在我所有的视图中访问某些ViewBag属性?我想获得一些信息,例如当前用户名等,可在任何地方访问,但不必在我的项目中的每个ActionResult方法中专门定义属性
How can I access some ViewBag properties across all my views? I want to have some information like current user name, etc accessible everywhere, but without having to to specifically define the properties in each ActionResult method on my project
推荐答案
达到要求的最佳,直接的方法是制作一个自定义基础控制器"并从该基础控制器继承您的控制器.
The best and straight forward way to accomplish your requirement is to make a Custom Base Controller and inherit your Controller from this Base Controller.
public class MyBaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.someThing = "someThing"; //Add whatever
base.OnActionExecuting(filterContext);
}
}
现在,代替继承Controller
类,在控制器中继承MyBaseController
,如下所示:-
Now instead of inheriting Controller
class,inherit MyBaseController
in your Controller as shown :-
public class MyOtherController : MyBaseController
{
public ActionResult MyOtherAction()
{
//Your Stuff
return View();
}
//Other ActionResults
}
这篇关于在所有视图上访问Viewbag属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!