Blaise
Blaise

Reputation: 22212

Is it possible to add a view model on the _layout.cshtml?

The scenario is that I want to populate the navigation bar, the menu, with Mvc.Sitemap.

How should I achieve this?

It feels strange to add a View Model onto the layout page. And that may cause a view to have more than one View Models.

can any one help? Thank you.

Update: ---------- I have Home/_Menu as a partial view which uses MenuViewModel. But how can I include that View in _layout?

I cannot simply use @Html.Partial("_Menu") inside my _Layout.cshtml because I need to specify the controller and action where the view model is built. What is the correct way to do this?

And if I do @Html.RenderAction("_Menu", "Home"), I get a Object reference not set to an instance of an object. error on the Model.

Upvotes: 0

Views: 1052

Answers (1)

bobek
bobek

Reputation: 8020

You should not have a model in your Layout, because then every view that you call from there by default will have this model. Instead you should create a Menu view with the model, and when you call it pass a new MenuModel to it as a model.

Edit: You can have a class that will pull data out of where you store your menu values. Then you call your partial like this:

@Html.Partial("_Menu_", menuobject.Root)

And the class:

partial class menuobject
{
    public static menuobject Root
    {
        // MenuRoots are all roots that have ID -1 - which will be the root
        return MenuRoots.Single(x => x.Something == "Topnavi"); // this will return the root above all your menus
    }
}

Than in your view you go foreach() on each level of menus to populate them.

Upvotes: 1

Related Questions