I have this section defined in my _Layout.cshtml
@RenderSection("Scripts", false)
I can easily use it from a view:
@section Scripts {
@*Stuff comes here*@
}
What I'm struggling with is how to get some content injected inside this section from a partial view.
Let's assume this is my view page:
@section Scripts {
<script>
//code comes here
</script>
}
<div>
poo bar poo
</div>
<div>
@Html.Partial("_myPartial")
</div>
I need to inject some content inside the Scripts
section from _myPartial
partial view.
How can I do this?
I had a similar problem, where I had a master page as follows:
but the partial view depended on some JavaScript in the Scripts section. I solved it by encoding the partial view as JSON, loading it into a JavaScript variable and then using this to populate a div, so:
I solved this a completely different route (because I was in a hurry and didn't want to implement a new HtmlHelper):
I wrapped my Partial View in a big if-else statement:
Then, I called the Partial twice with a custom ViewData:
The goal of the OP is that he wants to define inline scripts into his Partial View, which I assume that this script is specific only to that Partial View, and have that block included into his script section.
I get that he wants to have that Partial View to be self contained. The idea is similar to components when using Angular.
My way would be to just keep the scripts inside the Partial View as is. Now the problem with that is when calling Partial View, it may execute the script in there before all other scripts (which is typically added to the bottom of the layout page). In that case, you just have the Partial View script wait for the other scripts. There are several ways to do this. The simplest one, which I've used before, is using an event on
body
.On my layout, I would have something on the bottom like this:
Then on my Partial View (at the bottom):
Another solution is using a stack to push all your scripts, and call each one at the end. Other solution, as mentioned already, is RequireJS/AMD pattern, which works really well also.
I had the similar problem solved it with this:
Thats a pretty way to inject i guesse.
Sections don't work in partial views and that's by design. You may use some custom helpers to achieve similar behavior, but honestly it's the view's responsibility to include the necessary scripts, not the partial's responsibility. I would recommend using the @scripts section of the main view to do that and not have the partials worry about scripts.
Using Mvc Core you can create a tidy TagHelper
scripts
as seen below. This could easily be morphed into asection
tag where you give it a name as well (or the name is taken from the derived type). Note that dependency injection needs to be setup forIHttpContextAccessor
.When adding scripts (e.g. in a partial)
When outputting the scripts (e.g. in a layout file)
Code