【问题标题】:asp.net set value of attribute with a namespace prefix. (xlink:href on svg/use element)asp.net 使用命名空间前缀设置属性值。 (xlink:svg/use 元素上的href)
【发布时间】:2018-04-16 21:26:36
【问题描述】:

我正在尝试使用use 元素将svg 放置在我的页面中,并使用外部引用,如下所示:

<svg class="xyz" width="25px" height="25px" fill="red" xmlns:xlink="http://www.w3.org/1999/xlink">
    <use id="useLogo" runat=server class="xyz" href="~/Content/images/test.svg#shape" xlink:href="~/Content/images/test.svg#shape"></use>
</svg>

问题是我在用户控件中执行此操作,因此我需要引用相对于应用程序的svg 文件,而不是用户控件所在的页面。

我决定在hrefxlink:href 属性中使用~ 字符,然后在page_load 上使用:

protected void Page_Load(object sender, EventArgs e) {
    this.useLogo.Attributes["href"] = Page.ResolveUrl(this.useLogo.Attributes["href"]);
    //this.useLogo.Attributes["xlink:href"] = Page.ResolveUrl(this.useLogo.Attributes["xlink:href"]);
}

这确实有效,但为了向后兼容,我需要对 xlink:href 属性做同样的事情。由于元素的AttributeCollection 没有该属性的项目,因此命名空间似乎正在绊倒 ASP.Net。有什么方法可以识别命名空间属性,还是有完全不同的方法来做到这一点?

【问题讨论】:

  • "this" 是页面 - 您正在查看 aspx 页面的 Page_Load 事件。所以useLogo对象就是页面上的“使用”元素。
  • 问题是“xlink:href”没有出现在元素的属性列表中。

标签: c# asp.net svg webforms xlink


【解决方案1】:

如果您在浏览器中运行您的应用程序并查看源代码,您会注意到xlink:href 已被剥离,您的控件呈现为:

<use id="MainContent_useLogo" class="xyz" href="~/Content/images/test.svg#shape"></use>

请注意,runat 属性也丢失了。所有这些都是 ASP 引擎处理标签的结果,它决定如何处理每个属性。

因为这两个属性已被剥离,所以 Attributes 属性不包括它们,而在您的情况下它只包括 classhref

由于您希望hrefxlink:href 属性具有相同的值,您可以简单地以编程方式添加xlink:href 属性并将其设置为href 属性的值:

useLogo.Attributes["href"] = ResolveUrl(this.useLogo.Attributes["href"]);
useLogo.Attributes.Add("xlink:href", useLogo.Attributes["href"]); 

【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 2023-03-11
    相关资源
    最近更新 更多