从代码隐藏中遍历DOM

时间:2011-09-29 19:26:17

标签: asp.net dom traversal code-behind

我有一个asp.net网页,其中包含一系列隐藏的输入字段,用于在提交时将值从客户端传送到代码behing。

<input type="hidden" id="zorro1" value="somevalue set at runtime from client-side" />
<input type="hidden" id="zorro2" value="somevalue set at runtime from client-side" />
.../... 
<input type="hidden" id="zorron" value="somevalue set at runtime from client-side" />

现在我需要从代码隐藏中提取这些值。 我可以写出这个丑陋的东西:

dim aValue as string = zorro1.value
dim aValue as string = zorro2.value
.../...
dim aValue as string = zorron.value

它可以工作,但我希望用伪代码“查找”这样的每个隐藏输入,使用LINQ:

dim inputControls = from c in page.controls where id.startswith("zorro") select s

for each ic in inputControls
    aValue = ic.value
    aId = ic.ID
next

有人能让我朝着正确的方向前进吗?

1 个答案:

答案 0 :(得分:0)

在网络上的某个地方找到了这个答案,它有效:

在HTML页面本身中,您可以在方便时添加对象,例如:

<input type="hidden" id="someMeaningfulID" runat="server" value="some Value" />

从Javascript中可以轻松更改此类对象的值。 在你的代码中,添加这个子:

    Private Sub AddControls(ByVal page As ControlCollection, ByVal controlList As ArrayList)
    For Each c As Control In page
        If c.ID IsNot Nothing Then
            controlList.Add(c)
        End If

        ' A pinch of recursivity never hurts :-)
        If c.HasControls() Then
            call AddControls(c.Controls, controlList)
        End If
    Next
End Sub

当你需要它时:

Dim controlList As New ArrayList()
Call AddControls(Page.Controls, controlList)

For Each c In controlList
        If c.id.startswith("something I'm looking for") Then ...

        If c.value <> "" Then....

        If c.someProperty = someValue tThen...
.../...