Given views hierarchy: Index.cshtml -> _Layout.cshtml -> _MasterLayout.cshtml :
_MasterLayout.cshtml - the set of sections which I want to use in master layout (below)
@section javascriptLinks {
<script src="~/client/vendor/require-jquery.js" data-main="~/client/main.js" type="text/javascript"></script>
}
@RenderBody()
_Layout.cshtml - actual site master layout
@{
Layout = "~/Views/Shared/_MasterLayout.cshtml";
}
<!doctype html>
<html>
<!-- actual site layout here -->
<body>
@RenderBody()
@RenderSection("javascriptLinks")
</body>
</html>
Index.cshtml - some concrete page specific markup
The idea of splitting _Layout.cshtml and _MasterLayout.cshtml is code sharing. I have a kind of library/framework and _MasterLayout belongs to this library. And _Layout.cshtml is a concrete application site master layout.
Unfortunately, this schema doesn't work. During rendering _Layout.cshtml won't see sections from _MasterLayout.cshtml.
Is there any way to use sections in such a case (taking them from a parent View not from a child View)?
One possible solution I can see is creating separate pages for each section in my _MasterLayout.cshtml and call @RenderPage in _Layout. But, I'd like to have a single sharing asset (_MasterLayout.cshtml).
Try to reverse the operation. I mean like this:
your _MasterLayout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
@RenderSection("HeadSection", true)
<title>@ViewBag.Title</title>
</head>
<body>
@RenderBody()
// ......
// You could put your general scripts here
<script src="~/client/vendor/require-jquery.js" data-main="~/client/main.js" type="text/javascript"></script>
// Put true to enforce the sub layout to define Scripts section
@RenderSection("Scripts", true)
</body>
</html>
Your _Layout.cshtml:
@{ Layout = "~/Views/_Shared/_LayoutMain.cshtml"; }
@section HeadSection{
// any thing you want
@RenderSection("HeadSection", false)
}
@RenderBody()
// ......
// Put false to make Scripts section optional
@section Scripts{
@RenderSection("Scripts", false)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With