Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a script bundle conditionally?

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.

like image 613
Shai Cohen Avatar asked Feb 11 '14 16:02

Shai Cohen


People also ask

What is difference between bundling and minification?

Both bundling and minification are the two separate techniques to reduce the load time. The bundling reduces the number of requests to the Server, while the minification reduces the size of the requested assets.

How do you override the bundling setting of web config?

To enable bundling and minification, set the debug value to "false". You can override the Web. config setting with the EnableOptimizations property on the BundleTable class. The following code enables bundling and minification and overrides any setting in the Web.

What is BundleConfig Cs in MVC?

BundleConfig.cscs file present in a default MVC5 application. This file contains RegisterBundles() method which is being called at Application_Start() event by global. asax. cs file. This RegisterBundles() method contains all the bundles created in the application.


1 Answers

The ViewBag should not be necessary...

Using appSettings from web.config you don't need to recompile for testing and it deploys easily.

<appSettings>
    <add key="TestingEnabled" value="true" />
</appSettings>

View or Layout

@{
    bool testing = Convert.ToBoolean(
        System.Configuration.ConfigurationManager.AppSettings["TestingEnabled"]);
}

@if (testing) {
    @Scripts.Render("~/bundles/testing")
}

And I would define "~/bundles/testing" in BundleConfig regardless of the testing condition unless you wish to bundle this with other scripts.

If you assigned Properties.Default.IsEnabledTestingFeatures from AppSettings then the root of your problem is how you implemented your Properties.

like image 178
Jasen Avatar answered Sep 21 '22 14:09

Jasen