按自定义属性访问元素

时间:2014-12-02 10:12:15

标签: c# html asp.net custom-attributes

我想知道我是否能够通过自定义属性名称从后面的代码中访问Html中的aspx个元素。像

HtmlElement[] allElements = Page.FindElementByCustomName("custom-name");

它会给我一个包含该属性的所有元素的数组,假设我的aspx如下所示

<a runat="server" custom-name = "any">Faf</a>
<a runat="server">AB</a>
<a runat="server" custom-name = "any">Amla</a>

allElements将有两个a元素,即

<a runat="server" custom-name = "any">Faf</a>
<a runat="server" custom-name = "any">Amla</a>

有可能吗?

1 个答案:

答案 0 :(得分:2)

您可以遍历页面中的所有控件,但必须以递归方式完成。例如,从Page.Controls开始,然后,对于每个控件,迭代其Controls集合。对于控件来获取属性,它需要实现IAttributeAccessor;您可以检查迭代中的控件是否实现了此接口。当您在标记上插入自定义属性时,它是一个必需的接口。例如,WebControl实现它。如果现在,当您尝试添加自定义属性时,ASP.NET将失败,表示没有具有该名称的属性。 类似的东西:

public static void ListControls(ControlCollection controls, List<Control> controlsFound)
{
    foreach (var control in controls.OfType<Control>())
    {
        if (control is IAttributeAccessor)
        {
            controlsFound.Add(control);
            ListControls(control.Controls, controlsFound);
        }
    }
}

您应该从您的页面致电:

var controlsFound = new List<Control>();
ListControls(this.Controls, controlsFound);

最后,只需遍历controlsFound,你知道它是IAttributeAccessor和retrieve属性name-name的集合:

var attr = (control as IAttributeAccessor).GetAttribute("attribute-name");