My code compiles and runs without errors; however, it doesn't render as I expected.
The Theory:
I want to use multiple layout pages.
The "base" layout should only include the style and javascript files that are being used by the solution.
The other layout should have the html content or wrappers. This layout seems superfluous currently, but my superior assures me it will lead to future greatness. Such as having multiple headers or the ability to not have headers or footers on certain pages. The main things is to have multiple ContentLayouts but one common BaseLayout
The Code:
_BaseLayout
<html>
<head>
<link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="@Url.Content("~/Scripts/common.js")"></script>
@RenderSection("JavaScript", false)
@RenderSection("Css", false)
</head>
<body>
@RenderBody()
</body>
</html>
_ContentLayout
@{
Layout = "~/Views/Shared/_BaseLayout.cshtml";
}
@RenderSection("JavaScript", false)
@RenderSection("Css", false)
<div class="page">
<section class="wrapper">
@RenderBody()
</section>
</div>
View.cshtml
@{
Layout = "~/Views/Shared/_ContentLayout.cshtml";
}
@section JavaScript
{
<script type="text/javascript">
(function ($) {
$(function () {
//do stuff;
});
} (jQuery));
</script>
}
<div>
//html content
</div>
Like I stated earlier this works. The problem is when I view the page source the script from the view is rendered in the _ContentLayout and thus falls outside of the designated script area. Can I "kick" the script code to the next layout? This would allow all the script code to be in the same area.
You should develop views in respect to @RenderSection()
behavior.
Each @RenderSection()
renders its descendant @section SectionName { }
. So you need to change your Views in this order:
_BaseLayout.cshtml - Remains as it is.
_ContentLayout.cshtml:
@{Layout = "~/Views/Shared/_BaseLayout.cshtml";}
@section JavaScript {
@RenderSection("JavaScriptToHead", false)
}
@section Css {
@RenderSection("CssToHead", false)
}
<div class="page">
<section class="wrapper">
@RenderBody()
</section>
and finally View.cshtml:
@{Layout = "~/Views/Shared/_ContentLayout.cshtml";}
@section JavaScriptToHead {
//JS stuff
}
@section CssToHead {
//Css stuff
}
<div>
//html content
</div>
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