繁体   English   中英

如何使下拉列表中的必填字段验证器?

[英]How to make required field validator on dropdownlist?

我有一个下拉列表,在其中我为(选择频道...)添加了额外的值。 如果选择此值,则我希望显示一条必需的消息,我尝试的是:

<td>
    <asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
    runat="server" DataTextField="Description" DataValueField="ID">
   <asp:ListItem Value="-1" Text="Choose channel..." />
   </asp:DropDownList>
   <asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                                ControlToValidate="ServiceChannelDropDownList" 
                                InitialValue="-1"
                                ErrorMessage="*"                                 
    </asp:RequiredFieldValidator>
</td>

不幸的是,这只是让我选择了初始值(数据库中自然不存在该初始值)而没有说不允许这样做。 如何解决呢?

您需要在绑定Dropdownlist数据的(.cs)后面的代码中添加默认值,而不是在.aspx页中添加默认值

ServiceChannelDropDownList.DataBind();
ServiceChannelDropDownList.Items.Insert(0, new ListItem("Choose channel...","-1"));
<td>
    <asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
    runat="server" DataTextField="Description" DataValueField="ID">
   <asp:ListItem Value="0" Text="Choose channel..." />
   </asp:DropDownList>
   <asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                                ControlToValidate="ServiceChannelDropDownList" 
                                InitialValue="0"
                                ErrorMessage="*"                                 
    </asp:RequiredFieldValidator>
</td>

我需要将ValidationGroup添加到RequiredFieldValidator,例如,

<asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
                            ControlToValidate="ServiceChannelDropDownList"
                            InitialValue="0"
                            ErrorMessage="Channel is required."
                            ValidationGroup="WorkflowValidation" 
                            CssClass="ValidationCss" 
                            EnableTheming="false">*
                        </asp:RequiredFieldValidator>

谢谢大家的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM