如何有条件地添加脚本包?

Sha*_*hen 13 bundle asp.net-mvc-5

我有一个javascript包,我只想在测试时包含,而不是在代码部署到生产时.

我添加了一个名为的属性IsEnabledTestingFeatures.在BundleConfig.cs文件中,我这样访问它:

if(Properties.Settings.Default.IsEnabledTestingFeatures) {
    bundles.Add(new ScriptBundle("~/bundles/testing").Include("~/Scripts/set-date.js"));
}
Run Code Online (Sandbox Code Playgroud)

这工作正常.

现在,如果此属性设置为true ,我只想在我的页面中包含该包.

我尝试了以下,但编译器抱怨它无法找到Default命名空间:

@{
    if( [PROJECT NAMESPACE].Properties.Default.IsEnabledTestingFeatures)
    {
        @Scripts.Render("~/bundles/testing")
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图找到如何Scripts.Render从Controller本身访问功能,但一直没有成功.

我更喜欢在视图中添加bundle,但是会通过Controller添加它.

Jas*_*sen 10

ViewBag不应该是必要的...

使用appSettingsweb.config中你不需要重新编译和测试很容易部署.

<appSettings>
    <add key="TestingEnabled" value="true" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

查看或布局

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

@if (testing) {
    @Scripts.Render("~/bundles/testing")
}
Run Code Online (Sandbox Code Playgroud)

而我所界定"~/bundles/testing"BundleConfig,除非你想与其他脚本捆绑这个无论试验条件.

如果您是Properties.Default.IsEnabledTestingFeatures从AppSettings 分配的,那么问题的根源就是您实现属性的方式.


Sha*_*hen 5

直到希望提出另一种[read:better]解决方案,我已经使用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"));
}
Run Code Online (Sandbox Code Playgroud)

调节器

public ActionResult Index()
{
    ViewBag.IsEnabledTestingFeatures = Properties.Settings.Default.IsEnabledTestingFeatures;
    return View();
}
Run Code Online (Sandbox Code Playgroud)

视图

@if (ViewBag.IsEnabledTestingFeatures != null && ViewBag.IsEnabledTestingFeatures)
{
    @Scripts.Render("~/bundles/site")
}
Run Code Online (Sandbox Code Playgroud)

一些说明:

  1. 我没有通过ViewModel中的属性实现此功能,因为此属性/功能独立于显示的数据.将此条件与单个数据模型相关联似乎是不正确的,因为它是站点范围的功能.

  2. 我使用了应用程序级设置,因为由于我们利用Web转换,因此在每个环境的基础上配置此属性会更容易.因此,每个环境都可以根据需要设置此属性.