How do I add a script bundle conditionally?
asp.net-mvc-5, bundle
Solution
Until, hopefully, an alternative [read: better] solution is proposed, I have implemented it using ViewBag.
BundleConfig.cs
//if testing features are enabled (eg: "Set Date"), include the necessary scripts
if(Properties.Settings.Default.IsEnabledTestingFeatures)
{
bundles.Add(new ScriptBundle("~/bundles/testing").Include(
"~/Scripts/set-date.js"));
}
Controller
public ActionResult Index()
{
ViewBag.IsEnabledTestingFeatures = Properties.Settings.Default.IsEnabledTestingFeatures;
return View();
}
View
@if (ViewBag.IsEnabledTestingFeatures != null && ViewBag.IsEnabledTestingFeatures)
{
@Scripts.Render("~/bundles/site")
}
Some Notes:
I did not implement this via a property in the ViewModel due to this property/feature being independent of the data being displayed. It seemed incorrect to associate this condition with individual data models as it is a site-wide feature.
I used application-level settings because it will be easier to configure this property on a per-environment basis due to the fact we utilize web transforms. Thus each environment can set this property as needed.
Problem
I have a javascript bundle that I only want to include when testing, not when the code is deployed to production. I have added a Property called `IsEnabledTestingFeatures`. In the BundleConfig.cs file I access it like so: ``` if(Properties.Settings.Default.IsEnabledTestingFeatures) { bundles.Add(new ScriptBundle("~/bundles/testing").Include("~/Scripts/set-date.js")); } ``` This works correctly. Now, I only want to include the bundle in my page if this property is set to true. I have tried the following, but the compiler is complaining that it cannot find the `Default` namespace: ``` @{ if( [PROJECT NAMESPACE].Properties.Default.IsEnabledTestingFeatures) { @Scripts.Render("~/bundles/testing") } } ``` I tried finding how to access the `Scripts.Render` functionality from the Controller itself, but have been unsuccessful. I prefer to add the bundle in the view itself, but will settle for adding it via the Controller.