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?
This is quite a popular question, so I'll post my solution up.
I had the same problem and although it isn't ideal, I think it actually works quite well and doesn't make the partial dependant on the view.
My scenario was that an action was accessible by itself but also could be embedded into a a view - a google map.
In my
_layout
I have:In my
index
view I have:In my
clients
view I have (all the map and assoc. html):My
Clients_Scripts
view contains the javascript to be rendered onto the pageThis way my script is isolated and can be rendered into the page where required, with the
body_scripts
tag only being rendered on the first occurrence that the razor view engine finds it.That lets me have everything separated - it's a solution that works quite well for me, others may have issues with it, but it does patch the "by design" hole.
This worked for me allowing me to co-locate javascript and html for partial view in same file. Helps with thought process to see html and related part in same partial view file.
In View which uses Partial View called "_MyPartialView.cshtml"
In Partial View file
You can't need using sections in partial view.
Include in your Partial View. It execute the function after jQuery loaded. You can alter de condition clause for your code.
Julio Spader
Pluto's idea in a nicer way:
CustomWebViewPage.cs:
Views\web.config:
View:
Partial (_BackendSearchForm.cshtml):
Layout page: