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

后端 未结 8 2200
故里飘歌
故里飘歌 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:13

    Since ViewBag properties are, by definition, tied to the view presentation and any light view logic that may be necessary, I'd create a base WebViewPage and set the properties on page initialization. It's very similar to the concept of a base controller for repeated logic and common functionality, but for your views:

        public abstract class ApplicationViewPage : WebViewPage
        {
            protected override void InitializePage()
            {
                SetViewBagDefaultProperties();
                base.InitializePage();
            }
    
            private void SetViewBagDefaultProperties()
            {
                ViewBag.GlobalProperty = "MyValue";
            }
        }
    

    And then in \Views\Web.config, set the pageBaseType property:

    
        
        
          
            
            
            
            
          
        
      
    

提交回复
热议问题