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.cshtml
page to be a class called ApplicationBaseModel
and every other view model throughout the application must inherit from this class, and every action must set the appropriate data for the base model.
I don't mind simple inheritance in this way, it is the fact that in every single action method I must retreive the data and store it in the view model. Not a very elegant solution in my opinion.
Anyone have any ideas on other ways of solving this issue?
I would create a
BaseController
which retrieves the data in theInitialize()
override and sets it to aViewBag
property. Now derive every Controller you create fromBaseController
and in your layout use theViewBag
property to access your user 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 aViewBag
property.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.
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.