21

Can the shared layout view have a controller?

I need to pass it Model information from a Controller?

Or am I missing something here?

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
Pinch
  • 4,009
  • 8
  • 40
  • 60

2 Answers2

17

In the controller:

    public PartialViewResult Menu()
    {
        var ChargeTypes = db.ChargeTypes.ToList();
        return PartialView(ChargeTypes);
    }

And then its partial view:

@model IEnumerable<ProposalMaker.Models.ChargeType>

@foreach (var item in Model)
{
    <li>@item.Name</li>
}

Then in the shared partial view

@{Html.RenderAction("Menu","ChargeType");}

Thanks for the tip SLaks!

Pinch
  • 4,009
  • 8
  • 40
  • 60
5

To pass information to the layout, you will need to use a base view model that is used by all your view models. Your layout can then take this base model.

I have previously answered an SO question on this

Pass data to layout that are common to all pages

Which has a detailed example.

Community
  • 1
  • 1
Colin Bacon
  • 15,436
  • 7
  • 52
  • 72
  • 1
    +1 for a nice approach and thanks for your suggestion. Although, I used my own approach below. – Pinch Sep 16 '13 at 17:40