What you are looking for is an ActionFilter , and then override OnActionExecuting . Here is one of my ActionFilters that adds the currently logged in user to the ViewBag:
public class AppendUserActionFilterAttribute : ActionFilterAttribute { ... public override void OnActionExecuting(ActionExecutingContext filterContext) { User currentUser = _sessionManager.CurrentUser; dynamic viewBag = filterContext.Controller.ViewBag; viewBag.CurrentUser = currentUser; } ... }
Then you need to apply the attribute wherever you want it to happen. If you add it to an action, this action will receive the added entry in the ViewBag. If you add it to the controller, all its actions will receive it. If you add it to the base controller and turn on all its controllers, then all your actions in the entire application will receive it
[AppendUserActionFilter] public class MyController : Controller { public ActionResult Foo() { .... } }
Matt greer
source share