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


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

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

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

这工作正常。

现在,我只想 包括 如果此属性设置为true,则在我的页面中包。

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

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

我试着找到如何访问 Scripts.Render 控制器本身的功能,但都没有成功。

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


4409
2018-02-11 16:15


起源



答案:


ViewBag 不应该是......

运用 appSettings 从 web.config中 您无需重新编译进行测试,并且可以轻松部署。

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

查看或布局

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

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

我会定义 "~/bundles/testing" 在 BundleConfig 无论测试条件如何,除非您希望将其与其他脚本捆绑在一起。

如果你分配了 Properties.Default.IsEnabledTestingFeatures 从AppSettings然后问题的根源是你如何实现你的属性。


9
2018-02-12 19:49



希望我不止一次投票!这肯定是公认的答案。 (恕我直言) - Scott K. Fraley


答案:


ViewBag 不应该是......

运用 appSettings 从 web.config中 您无需重新编译进行测试,并且可以轻松部署。

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

查看或布局

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

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

我会定义 "~/bundles/testing" 在 BundleConfig 无论测试条件如何,除非您希望将其与其他脚本捆绑在一起。

如果你分配了 Properties.Default.IsEnabledTestingFeatures 从AppSettings然后问题的根源是你如何实现你的属性。


9
2018-02-12 19:49



希望我不止一次投票!这肯定是公认的答案。 (恕我直言) - Scott K. Fraley


直到希望提出另一种[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"));
}

调节器

public ActionResult Index()
{
    ViewBag.IsEnabledTestingFeatures = Properties.Settings.Default.IsEnabledTestingFeatures;
    return View();
}

视图

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

一些说明:

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

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


5
2018-02-12 18:28