【问题标题】:Get all HTML attributes for a ASP.NET WebForms Control获取 ASP.NET WebForms 控件的所有 HTML 属性
【发布时间】:2013-11-25 18:04:12
【问题描述】:

我们的应用程序使用了一些自定义控件,其中一些生成了一些相当复杂的 HTML 输出。我们现在开始使用 AngularJS,它利用自己的 HTML 属性,例如 ng-hide=""ng-show=""

我希望能够结合使用这些东西,以防止我们手动写出控件内的所有 HTML,维护属性的智能感知,并根据需要添加额外的 ng-* 属性.

假设我有一个名为button 的控件,它上面有一堆自定义属性。我想在这样的角度页面上使用它:

<MyControl:Button runat="server" Text="Save" state="Success" ng-show="CanBeSaved()" ng-click="Save()" />

它会输出以下 HTML

<button id="ctrl_1234" class="btn btn-success" ng-show="CanBeSaved()" ng-click="Save()">Save</button>

在控件内部,如何获取所有属性(即使是该控件不知道的属性)并仅添加与角度相关的属性?

我的第一次尝试/伪代码

Dim sb = New StringBuilder
Dim attrs = Me.Attributes.Keys

For Each a As String In attrs
    If a.StartsWith("ng-") Then
        sb.Append(" " + a)
    End If
Next

【问题讨论】:

  • 你的尝试有什么问题?
  • Attributes.Keys 看起来不像返回我所期望的,而且它不是可以迭代的。
  • 你还需要这个答案吗?您是在尝试获取服务器端属性的集合,例如(ID、Visible、Text、MyNewProperty 等),还是仅获取 HTML 属性,例如(state、ng-show 等?)
  • 两者都是。我想要使​​用控件时写在控件上的所有属性。那些已知的属性将已经被处理,但问题是就该控件而言,我正在“编造”新的属性/属性。我只想让他们通过。

标签: asp.net vb.net angularjs webforms


【解决方案1】:

我为 Page_Load 提供了一个简单的函数,它会列出 ASP 属性和 HTML 属性,如果这对你有帮助的话。我假设如果您以可迭代的形式看到这些内容,它将解决您的问题?

Public Sub PageLoad() Handles Me.Load

    ' source:
    ' http://msdn.microsoft.com/en-us/library/system.componentmodel.bindableattribute%28v=vs.110%29.aspx

    ' Show server-side properties
    Dim attributes = System.ComponentModel.TypeDescriptor.GetProperties(ControlID) ' Your Control ID
    For Each item As System.ComponentModel.PropertyDescriptor In attributes

        System.Diagnostics.Debug.Print("Name=" & item.Name)
        System.Diagnostics.Debug.Print("Category=" & item.Category)

        ' You could only show certain category if you specify property categories like:
        ' <Category("MyCategory")> _

        If item.Category = "MyCategory" Then
        End If

    Next

    ' source:
    ' I used your existing code to iterate the collection & print
    ' SHow HTML attrs
    Dim attrs As System.Web.UI.AttributeCollection = ControlID.Attributes ' Your Control ID
    For Each a As String In attrs.Keys
        System.Diagnostics.Debug.Print(a & "=" & attrs(a))
    Next

End Sub

【讨论】:

  • 添加了完全限定的命名空间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2011-03-26
  • 2011-11-06
  • 1970-01-01
  • 2011-12-06
  • 1970-01-01
相关资源
最近更新 更多