As promised
You can't render @section
's as it's not supported when rendered by Partial Views, until then you can do this trick:
in your _Layout.cshtml
write
@RenderSection("scripts", false)
@Html.RenderSection("scripts")
The first one is the default, the second line is your brand new way to render a section, I use both in my code...
Now let's add some code to our Partial View
instead of
@section scripts {
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
replace it with:
@Html.Section(
@<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>, "scripts"
)
@Html.Section(
@<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>, "scripts"
)
and our little helper that you just put inside your Models
folder and reference it in your Partial View and Layout Page
// using idea from http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates/5433722#5433722
public static class HtmlExtensions
{
public static MvcHtmlString Section(this HtmlHelper htmlHelper, Func<object, HelperResult> template, string addToSection)
{
htmlHelper.ViewContext.HttpContext.Items[String.Concat("_", addToSection, "_", Guid.NewGuid())] = template;
return MvcHtmlString.Empty;
}
public static IHtmlString RenderSection(this HtmlHelper htmlHelper, string sectionName)
{
foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
{
if (key.ToString().StartsWith(String.Concat("_", sectionName, "_")))
{
var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
if (template != null)
{
htmlHelper.ViewContext.Writer.Write(template(null));
}
}
}
return MvcHtmlString.Empty;
}
}
To render CSS, all you need to so is using other section name, for example:
In _Layout.cshtml
@Html.RenderSection("styles")
in your Partial Views
@Html.Section(
@<link rel="stylesheet" href="http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css">, "styles"
)
I hope this helps.