Jon
Jon

Reputation: 40062

Nested/Inheriting Layout pages not working

I have the following layout pages

_StyledLayout.cshtml:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />


    <title>@ViewBag.Title</title>

    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
    <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>

    @RenderSection("Head", false)
</head>
<body>
    @RenderBody()
</body>
</html>

_StyledPageLayout.cshtml:

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

@section Head
{
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>

}

@RenderBody()

Details.cshtml:

@using System.Data;

@model ASPNETMVC3.Models.ConfigModel
@{
    ViewBag.Title = "Details";
    Layout = "~/Views/Shared/_StyledPageLayout.cshtml";
}

@section Head
{
<script type="text/javascript">

        var oTable;

        $(document).ready(function () {  

            $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });

        });

    </script>
}

<h2>
    Details</h2>

In this setup when I go to Details I get the error: *The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_StyledPageLayout.cshtml": "Head".*

What am I doing wrong?

Upvotes: 0

Views: 955

Answers (2)

Russell Horwood
Russell Horwood

Reputation: 1044

Essentially the same as the accepted answer but a little neater if you don't require a default rendering would be...

@section Head
{
   @RenderSection("Head", false)
}

...where the 'false' indicates that the section is not required.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039160

_StyledPageLayout.cshtml:

@section Head
{
    @if (IsSectionDefined("Head"))
    {
        // If the view contains a Head section use that instead
        @RenderSection("Head")
    }
    else
    {
        // The view doesn't have a Head section => use some default output
        <script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
    }
}

Upvotes: 2

Related Questions