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

后端 未结 8 2180
故里飘歌
故里飘歌 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 01:54

    I have found the following approach to be the most efficient and gives excellent control utilizing the _ViewStart.chtml file and conditional statements when necessary:

    _ViewStart:

    @{
     Layout = "~/Views/Shared/_Layout.cshtml";
    
     var CurrentView = ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
    
     if (CurrentView == "ViewA" || CurrentView == "ViewB" || CurrentView == "ViewC")
        {
          PageData["Profile"] = db.GetUserAccessProfile();
        }
    }
    

    ViewA:

    @{
       var UserProfile= PageData["Profile"] as List;
     }
    

    Note:

    PageData will work perfectly in Views; however, in the case of a PartialView, it will need to be passed from the View to the child Partial.

提交回复
热议问题