Sadly, this is not possible by default to use section
as another user suggested, since a section
is only available to the immediate child
of a View
.
What works however is implementing and redefining the section
in every view, meaning:
section Head
{
@RenderSection("Head", false)
}
This way every view can implement a head section, not just the immediate children. This only works partly though, especially with multiple partials the troubles begin (as you have mentioned in your question).
So the only real solution to your problem is using the ViewBag
. The best would probably be a seperate collection (list) for CSS and scripts. For this to work, you need to ensure that the List
used is initialized before any of the views are executed. Then you can can do things like this in the top of every view/partial (without caring if the Scripts
or Styles
value is null:
ViewBag.Scripts.Add("myscript.js");
ViewBag.Styles.Add("mystyle.css");
In the layout you can then loop through the collections and add the styles based on the values in the List
.
@foreach (var script in ViewBag.Scripts)
{
<script type="text/javascript" src="@script"></script>
}
@foreach (var style in ViewBag.Styles)
{
<link href="@style" rel="stylesheet" type="text/css" />
}
I think it's ugly, but it's the only thing that works.
******UPDATE****
Since it starts executing the inner views first and working its way out to the layout and CSS styles are cascading, it would probably make sense to reverse the style list via ViewBag.Styles.Reverse()
.
This way the most outer style is added first, which is inline with how CSS style sheets work anyway.