Assume the following @section code for a dynamic script received from Controller/Model: (dotnet core v3)
string scriptHtml = ViewData["scriptData"];
@section Scripts {
@if(! string.IsNullOrEmpty(scriptHtml)){
<script type='text/javascript'>
@Html.Raw(scriptHtml)
</script>
<script type='text/javascript' src='~/js/appcore/site.reuse.js'></script>
}
}
I want to use this inside _Layout.cshtml, in other words: I want to be able to include a Scripts section inside _Layout.cshtml, that will be consistent across all pages that include it.
So basically, _Layout.cshtml should look like this (Only the Javascript section showed):
@section Scripts {
@if(! string.IsNullOrEmpty(scriptHtml)){
<script type='text/javascript'>
@Html.Raw(scriptHtml)
</script>
<script type='text/javascript' src='~/js/appcore/site.reuse.js'></script>
}
}
<footer class="border-top footer text-muted">
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false) <!-- not rendered because it is not in the parent 'ie. Index.cshtml' page....
When this @section is not inside _Layout.cshtml but moved to the parent razor page (for instance Index.cshtml) calling _Layout.cshtml it will be included correctly. This however means I will have to @section this script for every razor page.
What can I do to include a 'dynamic' Javascript script and make it reusable across all pages that use _Layout.cshtml?