Search code examples
asp.netasp.net-mvcasp.net-mvc-4razor

Access Viewbag property on all views


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


Solution

  • 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
    }