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?
If you do have a legitimate need to run some
js
from apartial
, here's how you could do it,jQuery
is required:You can use these Extension Methods: (Save as PartialWithScript.cs)
Use like this:
Example partial: (_MyPartial.cshtml) Put the html in the if, and the js in the else.
In your _Layout.cshtml, or wherever you want the scripts from the partials on to be rendered, put the following (once): It will render only the javascript of all partials on the current page at this location.
Then to use your partial, simply do this: It will render only the html at this location.
From the solutions in this thread, I came up with the following probably overcomplicated solution that lets you delay rendering any html (scripts too) within a using block.
USAGE
Create the "section"
Typical scenario: In a partial view, only include the block one time no matter how many times the partial view is repeated in the page:
In a partial view, include the block for every time the partial is used:
In a partial view, only include the block once no matter how many times the partial is repeated, but later render it specifically by name
when-i-call-you
:Render the "sections"
(i.e. display the delayed section in a parent view)
CODE
choicely, you could use a your Folder/index.cshtml as a masterpage then add section scripts. Then, in your layout you have:
and your index.cshtml:
and it will working over all your partialviews. It work for me
assume you have a partial view called _contact.cshtml, your contact can be a legal (name) or a physical subject (first name, lastname). your view should take care about what's rendered and that can be achived with javascript. so delayed rendering and JS inside view may be needed.
the only way i think, how it can be ommitted, is when we create an unobtrusive way of handling such UI concerns.
also note that MVC 6 will have a so called View Component, even MVC futures had some similar stuff and Telerik also supports such a thing...
Following the unobtrusive principle, it's not quite required for "_myPartial" to inject content directly into scripts section. You could add those partial view scripts into separate
.js
file and reference them into @scripts section from parent view.