问题描述:

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.

网友答案:

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:

  1. 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.

  2. 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.

网友答案:

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.

相关阅读:
Top