【问题标题】:How to make required field validator on dropdownlist?如何在下拉列表中制作必填字段验证器?
【发布时间】:2014-03-19 19:41:15
【问题描述】:

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

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

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

【问题讨论】:

  • 如何在后台代码中将数据库值绑定到 Dropdown?您需要在此处添加默认项
  • 问题是我不能在那里添加项目,因为主键是自动生成的,不能设置为特定值。或者我应该检查服务器端的 -1 值吗?

标签: c# asp.net drop-down-menu requiredfieldvalidator


【解决方案1】:

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

ServiceChannelDropDownList.DataBind();
ServiceChannelDropDownList.Items.Insert(0, new ListItem("Choose channel...","-1"));

【讨论】:

  • 它仍然没有显示消息。绑定服务器端或客户端没有区别。
  • @user2609980,你可以添加你的服务器端代码试过吗?
  • 我添加了解决方案。无需服务器端代码。我需要为 requiredfieldvalidator 实现一个 Validationgroup。
【解决方案2】:
<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>

【讨论】:

  • 这就是我现在拥有的? :-)
  • 你取了选择频道的值-1,我取了0。请再看我贴的代码
  • 谢谢。我明白了,我试过了,但这并没有什么不同。
  • 尝试 java-script 验证。
【解决方案3】:

我需要在RequiredFieldValidator中添加一个ValidationGroup,例如,

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

感谢大家的帮助!

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多