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, M
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 explicit priority
parameter that can be used to control ordering.
I extended this solution by adding methods for:
// use this for scripts to be placed just before the
tag public static string RequireFooterScript(this HtmlHelper html, string path, int priority = 1) { ... } public static HtmlString EmitRequiredFooterScripts(this HtmlHelper html) { ... } // use this for CSS links public static string RequireCSS(this HtmlHelper html, string path, int priority = 1) { ... } public static HtmlString EmitRequiredCSS(this HtmlHelper html) { ... }
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.