In my shared layout I would like to have a "scripts" section to stuff it with all the scripts needed for page functionality.
Layout.cshtml
<html>
<head>
<title>Test</title>
<script src="@Url.Content("~/Scripts/jquery-2.0.3.js")" type="text/javascript"> </script>
@RenderSection("Scripts", required: false)
</head>
<body>
@RenderBody()
</body>
</html>
So, my view loads a specific javascript, and I want it to be in "scripts" section, and it's working.
Index.cshtml
@model PlatformaPu.Areas.Inventura.Models.Home.Index
@section Scripts {
<script src="@Url.Content("~/Areas/Inventura/Scripts/Home/Index.js")" type="text/javascript"></script>
}
{CONTENT REMOVED FOR BREVITY}
@section Footer {
@Html.Partial("~/Views/Shared/_AppSelector.cshtml", Model.AppSelector)
}
Finally, my view renders a partial and I have a javascript that this partial loads.
_AppSelector.cshtml
@model PlatformaPu.Models.Shared._AppSelector
@section Scripts {
<script src="@Url.Content("~/Scripts/Shared/_AppSelector.js")" type="text/javascript"></script>
}
{CONTENT REMOVED FOR BREVITY}
...and this is NOT working - javascript tag is NOT rendered in "scripts" section
How can I do this?
As discussed in this question, it is not possible to use sections in a partial view:
You should add the script reference to the main view that references the partial.
This is my first answer!
I've being working with webforms for years and now i'm dealing with MVC 5. Bit hard.
Perhaps is the wrong solution, but works :)
In Layout.cshtml. add second "ScriptsPartial" section
In Index.cshtml, add ", new ViewDataDictionary(ViewData) { { "ViewPage", this } }"
In _AppSelector.cshtml, remove this
In _AppSelector.cshtml, add this in any place
Just "send" the View to the PartialView (no Parent property like in WebForms?) and use it to add content to "ScriptsPartial" section.
"ScriptsPartial" is needed because DefineSection throws an error "section already defined: Scripts"
So, no more than one PartialView can use "ScriptsPartial" section... not so good solution.
Best regards,
Paco Ferre