asp.net 设置具有命名空间前缀的属性值。 (svg/use 元素上的 xlink:href)

asp.net set value of attribute with a namespace prefix. (xlink:href on svg/use element)

我正在尝试使用 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 属性做同样的事情。命名空间似乎被 ASP.Net 绊倒了,因为元素的 AttributeCollection 没有该属性的项。是否有某种方法可以识别命名空间属性,或者是否有一种完全不同的方法来做到这一点?

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

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

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

因为这两个属性被删除,Attributes 属性不包括它们,它只包括你的情况下的 classhref

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

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