【发布时间】:2017-05-10 04:07:53
【问题描述】:
我在 ASP.NET 中使用 CustomValidator,如下所示。
<asp:CustomValidator ID="AnswerCV" runat="server" ForeColor="Red"
ValidateEmptyText="True" ValidationGroup="test"
OnServerValidate="CustomValidation" ControlToValidate="TextBox1" Enabled="True"
ErrorMessage="You must fill in the text box.">
</asp:CustomValidator>
<asp:TextBox ID="TextBox1" ValidationGroup="test" runat="server">
</asp:TextBox>
<asp:Button runat="server" Id="Button" CausesValidation="True" ValidationGroup="test"
OnClick="Button_Click" />
在我后面的代码中
protected void CustomValidation(object sender, ServerValidateEventArgs e)
{
MessageBox.Show("It is firing!!!");
if (string.IsNullOrEmpty(TextBox1.Text))
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
}
而按钮点击方法如下
protected void Button_Click(object sender, EventArgs e)
{
MessageBox.Show("I should not have fired.");
}
CustomValidation 方法会触发,但Button_Click 方法会在此之后触发,然后是“您必须填写文本框”。错误信息显示。如何防止Button_Click 方法触发,当文本框为空时验证失败并触发错误消息,但在Button_click 方法触发之后?
stackoverflow 页面here 提供了我已经实现但仍然触发 Button_Click 方法的其他解决方案。
除此之外: 我不能使用客户端解决方案,因为我将在 Init() 方法中动态添加代码,该方法通过 CheckedChanged 事件启用和禁用 CustomValidator只有某些单选按钮。 结束
我还尝试了不使用OnServerValidate 方法的CustomValidator,并且我尝试从CustomValidation 方法返回布尔值false 会导致语法错误。
【问题讨论】:
-
尝试在你的按钮上设置 input type='button'
-
将我的 asp:Button 设置为 type = 'button' 但这并没有解决问题。我也需要它是一个 asp:Button。
-
尝试将属性
UseSubmitBehavior设置为false,如buttonName.UseSubmitBehavior = false;或在您的代码中可能如Id="Button" CausesValidation="True" UseSubmitBehavior="False"? -
我尝试了这些建议,但仍然无法正常工作。谢谢。
-
目的只是验证TextBox是否为空???
标签: c# asp.net customvalidator