I am working with MVC v4.
I have a '_BootstrapLayout' page which defines all the twitter bootstrap etc stuff, A main page which defines the site layout, navbar etc, and site pages which inherit from main page.
_BootstrapLayout.cshtml
_MainPage.cshtml @{ Layout = "~/Views/Shared/_BootstrapLayout.cshtml"; }
Index.cshtml @{Layout = "~/Views/Shared/_MainPage.cshtml";}
So Master Page --> Main Page --> site Page(s)
The _BootstrapLayout page contains a rendersection for scripts
@RenderSection("scripts", required: false)
I want to add a scripts section to the Index.cshtml page, but when I do I get the exception
@section scripts {
<script type="text/javascript">
$(document).ready(function () {
...
});
</script>
}
The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_MainPage.cshtml": "scripts".
So I added an empty @section scripts to the _MainPage.cshtml, still the same problem ? Even if I add code to the _MainPage scripts section I still get the same error. It doesn't matter where I put the @section in _MainPage, still get the same error.
If I purposely don't close the section (ie, delete the }) then I get an error which indicates that the section is incorrect, so it's parsing the section in _MainPage.
How can I get @RenderSections for scripts on the site pages to work in this case ?
On your layout page, if required is set to false : @RenderSection("scripts", required: false) , when the page renders and the user is on the about page, contacts. js won't render. If required is set to true : @RenderSection("scripts", required: true) , When page renders and user is on the About page, contacts.
RenderSectionAsync(String) In layout pages, asynchronously renders the content of the section named name . RenderSectionAsync(String, Boolean) In layout pages, asynchronously renders the content of the section named name .
You'll need to redefine the section in _MainPage.cshtml
.
_BootstrapLayout.cshtml
@RenderSection("scripts", false)
_MainPage.cshtml
@section scripts
{
@RenderSection("scripts", false)
}
Index.cshtml
@section scripts
{
<script>
// etc.
</script>
}
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