【问题标题】:Multiple ScriptControl instances sharing variable多个 ScriptControl 实例共享变量
【发布时间】:2010-10-20 18:51:42
【问题描述】:

我有一个ScriptControl,它使用图像作为嵌入资源和GetWebResourceUrl 来生成WebResource.axd URL。我目前正在使用GetScriptDescriptors() 将 URL 发送到 JavaScript 对象。

ScriptControl 可以在 Repeater 中,因此您可能有 20 多个实例。它们都使用相同的图像(不能通过属性自定义),所以我想在变量中设置一次 URL 并共享它。我知道我可以用全局变量注册一个脚本块,但如果可能的话想避免这种情况。有没有办法在控件类型(全局->控件类型->控件实例)范围内设置变量?

【问题讨论】:

    标签: asp.net scope scriptcontrol


    【解决方案1】:

    这似乎运作良好:

            string imagesScript = String.Format(
                "MyNamespace.MyClass.prototype.imgDisabled = '{0}';" +
                "MyNamespace.MyClass.prototype.imgEnabled = '{1}';",
                Page.ClientScript.GetWebResourceUrl(typeof(MyClass), "MyNamespace.disabled.png"),
                Page.ClientScript.GetWebResourceUrl(typeof(MyClass), "MyNamespace.enabled.png")
            );
    
            Page.ClientScript.RegisterStartupScript(typeof(MyClass), "Images", imagesScript, true);
    

    然后在我的对象中,我只需执行 this.imgDisabledthis.imgEnabled 即可获取 URL。

    编辑:另一个选项是在 AssemblyInfo.cs 中将 JavaScript 引用设置为 WebResource(..., PerformSubstitution = true),然后您的 .js 文件可以在任何您希望的位置包含 <%= WebResource("MyNamespace.enabled.png") %>。这可以是您实际使用它或添加到对象原型的地方。

    【讨论】:

    • 第一种方式具有最大的灵活性(例如,允许带有属性的自定义图像 URL),所以我正在使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多