Access Viewbag property on all views

后端 未结 4 822
独厮守ぢ
独厮守ぢ 2021-02-14 02:22

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 specifi

4条回答
  •  青春惊慌失措
    2021-02-14 03:01

    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);
        }
    }
    

    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
    }
    

提交回复
热议问题