I’m using MVC3 (with Razor Syntax).
Here’s what I’m going for: part of my shared/_Layout.cshtml which looks in the ViewBag for a List<RelatedLinks>, if it’s there it renders a list of related links in the page toolbar (unsurprisingly). Some of my pages will populate this collection, some wont. When I populate the bag from my controller it works beautifully.
However, the controller doesn’t seem like the right place for these to be defined, they’re specific to a view and they feel like navigation logic – so I’d like to define them within the view markup.
I’ve tried adding them to the ViewBag from within the view, but it doesn’t seem to work. Even if I declare a section on my _Layout.cshtml that comes before the area which renders the links, the collection appears to be empty. Either I’m doing something wrong, or they don’t allow me to fill the ViewBag from within the view (which would make sense).
What my problem boils down to is this: I want my pages to signal to the _Layout.cshtml when they want that section rendered, and provide the list of links. I don’t want my child pages to worry about how we’re populating or drawing the list – I only want it to define what’s in the list. Any ideas? I’ve tried quite a few things (HtmlHelpers, sub-classing controller, etc) but I think I’m missing something obvious.
Instead of having
_Layout.cshtmlrender the links, why not create a partial view instead?In _Layout, add an optional section
In your view,
Your views can worry about populating the list, while your partial can handle the actual rendering.