Most elegant way to ensure view model data for _Layout.cshtml

前端 未结 3 1081

In my application I have some basic user information that needs to be displayed on every page (name, profile img). At the moment I have simply set the model in the _Layout

相关标签:
3条回答
  • 2021-02-04 10:36

    Depending on when you want to generate the ViewBag data you could also use the functions OnActionExecuting or OnActionExecuted. This might be more suitable because some data might not be available at the time the Controller is created.

    public class MyController : Controller
    {
        //Executes before every action
        protected override void OnActionExecuting(ActionExecutedContext context) 
        {
            //Call the method from the base class
            base.OnActionExecuting(context);
    
            //Create the ViewBag data here
            ViewBag.XYZ = XYZ();
        }
    
        //Executes after every action
        protected override void OnActionExecuted(ActionExecutedContext context) 
        {
            //Call the method from the base class
            base.OnActionExecuted(context);
    
            //Create the ViewBag data here
            ViewBag.XYZ = XYZ();
    
        }
    }
    
    0 讨论(0)
  • 2021-02-04 10:46

    Another option would be to rip out the parts of the layout view that require data, and place them into partials. Then from your layout view make an Html.Action call to actions that return those partials with the necessary viewmodel data.

    0 讨论(0)
  • 2021-02-04 10:56

    I would create a BaseController which retrieves the data in the Initialize() override and sets it to a ViewBag property. Now derive every Controller you create from BaseController and in your layout use the ViewBag property to access your user data.

    public class BaseController : Controller
    {
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
    
            // retireve data
            var data = new ApplicationBaseModel();
    
            // set to viewbag
            ViewBag.UserData = data;
        }
    }
    

    This way you do not have to derive all your model classes from ApplicationBaseModel. You can have strongly typed views and additionally your user data as a ViewBag property.

    0 讨论(0)
提交回复
热议问题