【问题标题】:How do I inject a script URL containing an ampersand with ASP.NET?如何使用 ASP.NET 注入包含 & 符号的脚本 URL?
【发布时间】:2010-02-03 15:40:39
【问题描述】:

我有一个需要以编程方式将 JavaScript 引用注入页面的服务器控件。它是引用 Microsoft 的 Bing 地图控件,该控件需要将 &s=1 附加到脚本 URL 以通过 SSL 使用。问题在于.NET Framework 对属性进行编码并将& 更改为&(使用Reflector 验证)。在此之后的某个时间点,& 将被完全删除。

所需的脚本标签:

<script type="text/javascript"
  src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1">
</script>

尝试 1:

var clientScriptManager = this.Page.ClientScript;
if (!clientScriptManager.IsClientScriptIncludeRegistered(this.GetType(), "BingMapControl"))
{
 clientScriptManager.RegisterClientScriptInclude(
  this.GetType(), "BingMapControl",
  "https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1");
}

尝试 2:

HtmlGenericControl include = new HtmlGenericControl("script");
include.Attributes.Add("type", "text/javascript");
include.Attributes.Add("src",
 "https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1");
this.Page.Header.Controls.Add(include);

有什么想法吗?

【问题讨论】:

    标签: asp.net javascript encoding attributes


    【解决方案1】:

    所需的脚本标签:

    实际上,没有。其实你想要的脚本标签是:

    <script type="text/javascript" 
        src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&amp;s=1">
    </script>
    

    确实希望将&amp;amp; 编码为&amp;amp;。为什么?因为 HTML 标准是这么说的。例如,参见 XHTML 1.0 标准的 C.12. Using Ampersands in Attribute Values (and Elsewhere) 部分:

    为了确保文档与历史 HTML 用户代理和基于 XML 的用户代理兼容,文档中使用的要被视为文字字符的 & 符号必须将其自身表示为实体引用(例如“&amp;amp; ”)。例如,当a元素的href属性引用带参数的CGI脚本时,它必须表示为http://my.site.dom/cgi-bin/myscript.pl?class=guest&amp;amp;name=user而不是http://my.site.dom/cgi-bin/myscript.pl?class=guest&amp;name=user

    【讨论】:

      【解决方案2】:

      出于好奇...这段代码只是一个示例吗?如果需要在运行时设置一些动态部分,我通常只使用 RegisterClientScript 及其同类。否则,您可以将其静态写入 aspx、ascx 或 js 文件中。

      您是否尝试过 Literal 控件?我知道我最近做了这件事。我必须挖掘我的代码。

      【讨论】:

        【解决方案3】:

        似乎所有添加到 Header 的控件都是 html.encode-d Page.Header.Controls.Add

        快速解决方案是添加一个属性 ScriptUrl

        public string ScriptUrl
        {
        get
        {
        return "https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&s=1";
        }
        }

        在 aspx 中

        <head runat="server">
        <title></title>
        <script type="text/javascript" src="<%= ScriptUrl %>"></script>
        </head>

        仅此而已

        【讨论】:

          猜你喜欢
          • 2012-07-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-14
          • 1970-01-01
          • 2012-01-11
          • 2021-02-22
          相关资源
          最近更新 更多