Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 915
jcvandan Avatar asked Jun 07 '11 15:06

jcvandan


People also ask

How do I view Cshtml?

Right click the Index. cshtml file and select View in Browser. You can also right click the Index. cshtml file and select View in Page Inspector.

How do you pass view model to view?

The View Models can be passed to the View by creating a dynamic property in ViewBag. It can be passed using the Model Property of the ViewData. The Model property allows us to create the strongly typed Views using the @model directive.

How can we pass the data from controller to view in MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.


1 Answers

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.

like image 149
DanielB Avatar answered Nov 15 '22 16:11

DanielB