代码之家  ›  专栏  ›  技术社区  ›  Alex Angas Colin

如何在asp.net中插入包含与号的脚本url?

  •  4
  • Alex Angas Colin  · 技术社区  · 16 年前

    我有一个服务器控件,需要以编程方式将javascript引用注入到页面中。它引用了微软的必应地图控件 &s=1 附加到脚本url以便通过ssl使用。问题是.NET框架对属性进行编码并更改 & & (用反射器验证)。在那之后的某个时刻 & 完全移除。

    所需的脚本标记:

    <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);
    

    有什么想法吗?

    3 回复  |  直到 16 年前
        1
  •  4
  •   Heinzi    16 年前

    所需的脚本标记:

    <script type=“文本/javascript”
    src=“https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?V=6.2&S=1”>
    </脚本>

    实际上,不是。实际上,您想要的脚本标记是:

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

    想要 & 编码为 &amp; . 为什么?因为html标准就是这么说的。例如,请参见 C.12. Using Ampersands in Attribute Values (and Elsewhere) XHTML 1.0标准:

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

        2
  •  0
  •   Bryan    16 年前

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

    你试过文字控制吗?我知道我最近做了这件事。我得找出我的密码。

        3
  •  0
  •   Krzysztof Król    16 年前

    似乎添加到头的所有控件都是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>

    仅此而已

    推荐文章