简体   繁体   English

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

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

I have a dropdownlist where I added an extra value to (Choose channel...). 我有一个下拉列表,在其中我为(选择频道...)添加了额外的值。 If this value is selected I want a message displayed that is required, what I tried is: 如果选择此值,则我希望显示一条必需的消息,我尝试的是:

<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>

Unfortunately this just let me select the initial value (which naturally does not exist in the database) without saying it is not allowed. 不幸的是,这只是让我选择了初始值(数据库中自然不存在该初始值)而没有说不允许这样做。 How to solve this? 如何解决呢?

You need to add the default value in your code behind(.cs) where you bind Dropdownlist data, instead of doing it in .aspx page 您需要在绑定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>

I needed to add a ValidationGroup to the RequiredFieldValidator, eg, 我需要将ValidationGroup添加到RequiredFieldValidator,例如,

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

Thanks all for the help! 谢谢大家的帮助!

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

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