ASP.NET MVC 3, sections and multiple layout levels

asp.net-mvc-3layout

I can't find a way to make @section and @RenderSection() work with multiple level layouts. In my project I define a hierarchy of layouts:

~/Views/Shared/_Layout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <meta ... />
    <meta ... />

    <link href="..." rel="stylesheet" type="text/css" />
    <link href="..." rel="stylesheet" type="text/css" />

    @RenderSection("Stylesheet", false)
</head>
<body>
    <!-- lots of markup -->
    @RenderBody()

    <!-- more markup -->

    <script src="..." type="text/javascript" />
    <script src="..." type="text/javascript" />

    @RenderSection("JavaScript", false)
</body>
</html>

~/Views/Shared/_BaseLayout.cshtml (there are no definitions of JavaScript or Stylesheet sections):

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!-- lots of markup -->
@RenderBody()

~/Views/Shared/_CreateEditLayout.cshtml (again, no definitions of JavaScript or Stylesheet):

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!-- lots of markup -->
@RenderBody()

~Views/Profile/Edit.cshtml:

@model ...

@{
    Layout = "~/Views/Shared/_CreateEditLayout.cshtml";
}

@section JavaScript {
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            // lots of funny JS
        });
    </script>
}

My problem is that it is enough to just define @section JavaScript { } (it isn't necessary to write markup or JavaScript inside the section) for my Edit.cshtml stop been rendered. The error is the following: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_CreateEditLayout.cshtml": "JavaScript".

Any ideas what is going wrong? Thanks in advance.

Best Answer

It's not possible, only workarounds. Here is an answer to your question: Razor Nested Layouts with Cascading Sections