I have an ASP.NET MVC 4 site organized into multiple areas. Each area has a Views/Shared/_Layout.cshtml
view which references a common shared layout. In the common layout, I have a sidebar which contains a list of items. I would like the ability to have a shared list of items that can be accessed by all of the _Layout.cshtml
views in order to aggregate a set of links.
Area1/Views/Shared/_Layout.cshtml:
@{
SidebarItems.Add("Area1 Item");
Layout = "~/Views/Shared/_Layout.cshtml";
}
Views/Shared/_Layout.cshtml:
@{
SidebarItems.Add("Common Item");
}
<ul>
@foreach (var item in SidebarItems)
{
<li>@item</li> @* List should contain two items: "Area1 Item", and "Common Item" *@
}
</ul>
I have tried two approaches:
Create a custom
WebViewPage<T>
class for each area that inherits from a common customWebViewPage<T>
class and make theSidebarItems
collection a property of the common base class. This does not work as it appears that Razor allocates a newWebPageView
when moving between layouts.Create a static class with a static collection that each
_Layout
calls to add items. This successfully accumulates the list items, but, since it's a static class, its lifetime is tied to the Application Domain, which means that the sidebar accumulates items from every area that is visited across multiple requests, rather than being a per-request list.
I am considering using the HttpRequest.Items
property, but that seems like it would be too short-lived -- the list of items does not change across requests and is completely determined by the Area's view that is displayed.
The other alternative is to push the rendering of the list into a section
that is rendered in each Area's _Layout
. This is less than ideal, as I would like to have a single point in the code that renders the list, but is doable.
Suggestions?