How to set ViewBag properties for all Views without using a base class for Controllers?

后端 未结 8 2181
故里飘歌
故里飘歌 2020-11-28 01:21

In the past I\'ve stuck common properties, such as the current user, onto ViewData/ViewBag in a global fashion by having all Controllers inherit from a common base controlle

8条回答
  •  情歌与酒
    2020-11-28 02:01

    You could use a custom ActionResult:

    public class  GlobalView : ActionResult 
    {
        public override void ExecuteResult(ControllerContext context)
        {
            context.Controller.ViewData["Global"] = "global";
        }
    }
    

    Or even a ActionFilter:

    public class  GlobalView : ActionFilterAttribute 
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Result = new ViewResult() {ViewData = new ViewDataDictionary()};
    
            base.OnActionExecuting(filterContext);
        }
    }
    

    Had an MVC 2 project open but both techniques still apply with minor changes.

提交回复
热议问题