I want to keep all of my JavaScript code in one section; just before the closing body
tag in my master layout page and just wondering the best to go about it, MVC style.
For example, if I create a DisplayTemplate\DateTime.cshtml
file which uses jQuery UI's DateTime Picker than I would embed the JavaScript directly into that template but then it will render mid-page.
In my normal views I can just use @section JavaScript { //js here }
and then @RenderSection("JavaScript", false)
in my master layout but this doesn't seem to work in display/editor templates - any ideas?
You could proceed with a conjunction of two helpers:
and then in your
_Layout.cshtml
:and somewhere in some template:
@Darin Dimitrov and @eth0 answers to use with bundle extention usage :
The answer given in Populate a Razor Section From a Partial using the
RequireScript
HtmlHelper follows the same pattern. It also has the benefit that it checks for and suppresses duplicate references to the same Javascript URL, and it has an explicitpriority
parameter that can be used to control ordering.I extended this solution by adding methods for:
I like Darin's & eth0's solutions though since they use the
HelperResult
template, which allows for script and CSS blocks, not just links to Javascript and CSS files.I faced the same problem, but solutions proposed here work good only for adding reference to the resource and are not very suitable for inline JS code. I found a very helpful article and wrapped all my inline JS (and also script tags) in
And in the _Layout view placed
@Html.PageScripts()
just before closing 'body' tag. Works like a charm for me.The helpers themselves:
I liked the solution posted by @john-w-harding, so I combined it with the answer by @darin-dimitrov to make the following probably overcomplicated solution that lets you delay rendering any html (scripts too) within a using block.
USAGE
In a repeated partial view, only include the block one time:
In a (repeated?) partial view, include the block for every time the partial is used:
In a (repeated?) partial view, include the block once, and later render it specifically by name
one-time
:To render:
CODE
Install the Forloop.HtmlHelpers nuget package - it adds some helpers for managing scripts in partial views and editor templates.
Somewhere in your layout, you need to call
This will be where any script files and script blocks will be outputted in the page so I would recommend putting it after your main scripts in the layout and after a scripts section (if you have one).
If you're using The Web Optimization Framework with bundling, you can use the overload
so that this method is used for writing out script files.
Now, anytime you want to add script files or blocks in a view, partial view or template, simply use
The helpers ensure that only one script file reference is rendered if added multiple times and it also ensures that script files are rendered out in an expected order i.e.