Is there a way to replicate the behaviour of the @:Scripts/Styles.Render
helper from code behind?
If I reference the bundles by using the BundleTable.Bundles.ResolveBundleUrl
method, then bundling and minification occurs even with debug=true
. I've read other questions, and the solution seems far obvious, by using the previously mentioned helper. But in my case, I don't know the name of the bundle while in the aspx, and it's generated in runtime in the code behind.
So, I need to add the references in the head, from the code behind, and I can't find a way to do it.
Is there a way? Or will I be forced to do it in the .aspx file?
Yep!
This is what I do for Web Forms. This example adds resources to the <head>
but also works with any control for which Controls.Add()
works
For CSS:
System.Web.UI.WebControls.Literal lit = new System.Web.UI.WebControls.Literal();
lit.Text = System.Web.Optimization.Styles.Render("~/bundles/my_css").ToHtmlString();
Header.Controls.Add(lit);
For JS:
System.Web.UI.WebControls.Literal lit = new System.Web.UI.WebControls.Literal();
lit.Text = System.Web.Optimization.Scripts.Render("~/bundles/my_js").ToHtmlString();
Header.Controls.Add(lit);
Also - since ASPX is a subclass of codebehind, you theoretically COULD get to the bundle name from ASPX by making it a protected (or public) variable in the codebehind (but you didn't post all your code so I'm not sure what you're up to exactly).
You could also just render the script inline
<%: Scripts.Render("~/bundles/my_js") %>
This also may be of help for those who have come here later.
An alternate option without using a Literal Control:
ClientScript.RegisterStartupScript(typeof(Page), "MyJS", Scripts.Render("~/bundles/bundledJS").ToHtmlString(), false);
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