我在页面上有两个用户控件实例。两者都有字段和一个提交按钮。
我已经在字段和验证器上设置了验证组,但出于某种原因验证了两个用户控件的验证器是否已激活。
答案 0 :(得分:7)
此方法也有效:
Dim valGroup = String.format("{0}-validation", Guid.NewGuid())
rfv001.ValidationGroup = valGroup
rfv002.ValidationGroup = valGroup
rfv003.ValidationGroup = valGroup
rfv004.ValidationGroup = valGroup
rfv005.ValidationGroup = valGroup
btnSubmit.ValidationGroup = valGroup
您只需手动设置ValidationGroup
的值。
答案 1 :(得分:3)
您可以在UserControl中公开要从Page设置的属性ValidationGroup
。此值应存储在ViewState中,以便UserControl的每个实例都将获得不同的ValidationGroups(如果您的页面分配不同)。
例如:
Public Property ValidationGroup() As String
Get
Return CStr(ViewState("ValidationGroup"))
End Get
Set(ByVal value As String)
SetValidationGroupOnChildren(Me, value)
ViewState("ValidationGroup") = value
End Set
End Property
Private Sub SetValidationGroupOnChildren(ByVal parent As Control, ByVal validationGroup As String)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is BaseValidator Then
CType(ctrl, BaseValidator).ValidationGroup = validationGroup
ElseIf TypeOf ctrl Is IButtonControl Then
CType(ctrl, IButtonControl).ValidationGroup = validationGroup
ElseIf ctrl.HasControls() And ctrl.Visible = True Then
SetValidationGroupOnChildren(ctrl, validationGroup)
End If
Next
End Sub
如果在UserControl中需要不同的ValidationGroup,则上述递归函数将不起作用,然后您可以从代码隐藏中手动分配它。例如,将UserControl的ID(可能已足够)或ClientID放在相应控件的ValidationGroup属性之前。您可以调用此函数的好地方是PreRender
。