验证gridview控件内的下拉列表

时间:2012-05-09 19:41:46

标签: asp.net

进行测试我尝试过自定义验证

function ClientValidate(sender, args) { 
       //return false for testing...
       args.IsValid = false;

    }

 <asp:CustomValidator runat="server" ID="CustomValidator1" ControlToValidate="ddldetail"
                        Text="Please select" ValidateEmptyText="true"    
                        ClientValidationFunction="ClientValidate"  
                        Display="Dynamic">     
                    </asp:CustomValidator>

编辑:这是我想要发生的事情:

enter image description here

如何验证下拉列表,我已经完成了这么多次,但我在这里做错了什么?任何第二双眼睛都可能发现它?我试图验证下拉列表,如果用户没有选择任何帮助?

<asp:Button ID="btn" runat="server" Text="Submit" OnClick="btn_Click"  CausesValidation="true"/>

<asp:GridView ID="GVInputMapping" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
                     EnableModelValidation="True" onrowdatabound="GVInputMapping_RowDataBound">
                    <Columns>
                        <asp:BoundField DataField="Name" ControlStyle-Width="250px" HeaderText="Name" SortExpression="Name" />
                        <asp:TemplateField>
                            <ItemTemplate>
                        <asp:DropDownList runat="server" ID="ddldetail">
                        <asp:ListItem Selected="True" Value="0">Select me</asp:ListItem>
                        <asp:ListItem Value="1">abc</asp:ListItem>
                        <asp:ListItem Value="2">GHt</asp:ListItem>
                    </asp:DropDownList>
    <asp:RequiredFieldValidator ID="requiredDDL" runat="server" 
                        ControlToValidate="ddldetail" ErrorMessage="Please select" InitialValue="Select me"  Display="Dynamic"></asp:RequiredFieldValidator>

                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

1 个答案:

答案 0 :(得分:0)

您已将验证者的InitialValue设置为选择我,但该项目的实际上是0

<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Text="Select Me" Value="0" />
    <asp:ListItem Text="Foo" Value="1" />
    <asp:ListItem Text="Bar" Value="2" />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
    ControlToValidate="DropDownList1" 
    ErrorMessage="Please select" 
    InitialValue="0"        
    Display="Dynamic">
</asp:RequiredFieldValidator>

您还需要为每一行分配一个唯一的验证组,否则验证将在每一行开始。要分配唯一的验证组,您可以使用Id列:

ValidationGroup='<%# string.Format("Group_{0}", Eval("Id")) %>'

您可以将其添加到验证器和行中的按钮。