Let's say we had a scenario where our app was not going to use jqueryui, except for one particular editor template. If I want to avoid putting jqueryui onto every page (i.e. I don't want to include it in the bundle(s) that are loaded by default in my _Layout.cshtml), how could I have the editor template include the jqueryui.js and jqueryui.css files for me in a way that wouldn't result in multiple references to those files, and would put the references in the header or at the end of my body instead of inline?
Here's what I've tried in my editor template that didn't seem to work:
@System.Web.Optimization.Scripts.Render("~/bundles/jqueryui")
@System.Web.Optimization.Styles.Render("~/Content/jqueryuistyles")
This added the script and link tags, but it renders the tags once per use of the editor template, and it also renders them right in-line, so in my case, that's before jQuery has been loaded at the bottom of the body.
@section Scripts{ <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/jqueryui")"></script> }
This matches how I include the bundle in my _Layout.cshtml, but this apparently doesn't work from an editor template. Nothing was rendered at all, and even if it did, I think it'd still result in multiple references to the JavaScript file (1 per time that the editor template was called)
Seems like there should be a way to have an editor template trigger the inclusion of a JavaScript or css file that can tie into the bundles or at the very least the @section system. Anyone know how to do this?
One way to accomplish this may be to request required javascript files using current request context. For example within Editor template you may write something like this to request a javascript include
HttpContext.Current.Items["Required.Script"] = "~/myeditortemplate.js";
Then in layout just before rendering of any optional script section you may render required script by looking at current context
Scripts.Render(HttpContext.Current.Items["Required.Script"].ToString())
Where Scripts is making use of script bundles in MVC. Alternativly you can simply emit script tag point src to required script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With