用户控件中的控件是否可以由用户控件外的验证器验证?

时间:2015-08-31 19:14:03

标签: asp.net vb.net

我有一个用户控件,根据其他配置选择显示TextBox或DropdownList。

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="CustomRelationshipDropDown.ascx.vb" Inherits="CustomRelationshipDropDown" %>

<asp:TextBox ID="TextBox1" runat="server" MaxLength="20"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

代码隐藏:

<ValidationProperty("Value")>
<SupportsEventValidation()>
Partial Class CustomRelationshipDropDown
    Inherits UserControl

    Public Property Value() As String
        Get
            If GetList("RelationshipList") Is Nothing Then
                Return TextBox1.Text
            Else
                Return DropDownList1.SelectedValue
            End If
        End Get
        Set(ByVal Value As String)
            If GetList("RelationshipList") Is Nothing Then
                TextBox1.Text = Value
            Else
                DropDownList1.SelectedValue = Value
            End If
        End Set
    End Property

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim list As List(Of String) = GetList("RelationshipList")

        If list IsNot Nothing Then
            For Each item In list
                DropDownList1.Items.Add(item)
            Next
            DropDownList1.Visible = True
            TextBox1.Visible = False
        Else
            DropDownList1.Visible = False
            TextBox1.Visible = True
        End If
    End Sub
End Class

另一个页面使用该用户控件,我希望有一个RequiredValidator来验证文本框。

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
    </div>
    <div>
        <uc1:CustomRelationshipDropDown ID="CustomRelationshipDropDown1" runat="server" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="CustomRelationshipDropDown1"></asp:RequiredFieldValidator>
    </div>
    <asp:Button ID="Button1" runat="server" Text="Button" />
</form>

当我单击Button1时,第二个验证器没有找到第二个文本框为空。

enter image description here

我应该如何修改CustomRelationshipDropDown以便外部验证器可以验证其中的文本框?

1 个答案:

答案 0 :(得分:4)

这应该可以解决问题:

undefined method `cumulative_cost' for #<Array:0x007fe3e31844e8>

我的控制器很简单:

 <div>
        <uc1:WebUserControl1 runat="server" ID="WebUserControl1" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator2" ControlToValidate="WebUserControl1$TextBox2"></asp:RequiredFieldValidator>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="RequiredFieldValidator3" ControlToValidate="WebUserControl1$DropDownList1"></asp:RequiredFieldValidator>
 </div>

还尝试随机选择Visible = false,并且它可以正常工作。