0

我有一个带有一些自定义验证的表单。表单上有一个按钮,可以将用户带到“确认页面”以显示订单的所有详细信息。

页面验证

    <asp:TextBox ID="txtBillingLastName" Name="txtBillingLastName" 
runat="server"  CssClass="txtbxln required"></asp:TextBox>
    <asp:CustomValidator 
    ID="CustomValidatorBillLN" runat="server" 
    ControlToValidate="txtBillingLastName"
    OnServerValidate="CustomValidatorBillLN_ServerValidate"
    ValidateEmptyText="True">
    </asp:CustomValidator>

验证器代码

protected void CustomValidatorBillLN_ServerValidate(object sender, ServerValidateEventArgs args)
    {
        args.IsValid = isValid(txtBillingLastName);
    }

但是,如果我将 PostBackUrl 或 Response.Redirect 添加到按钮 onclick 方法,则所有验证控件都将被忽略。

我可以使用 onclick 方法调用所有验证方法,但这似乎不是一个优雅的解决方案。

我试过设置 CausesValidation=False 没有运气。

有什么建议么?

4

2 回答 2

1

检查此代码

void ValidateBtn_OnClick(object sender, EventArgs e) 
  { 
     // Display whether the page passed validation.
     if (Page.IsValid) 
     {
        Message.Text = "Page is valid.";
     }

     else 
     {
        Message.Text = "Page is not valid!";
     }
  }

  void ServerValidation(object source, ServerValidateEventArgs args)
  {
     try 
     {
        // Test whether the value entered into the text box is even.
        int i = int.Parse(args.Value);
        args.IsValid = ((i%2) == 0);
     }

     catch(Exception ex)
     {
        args.IsValid = false;
     }
  }

和 Html 端代码

<form id="Form1" runat="server">

  <h3>CustomValidator ServerValidate Example</h3>

  <asp:Label id="Message"  
       Text="Enter an even number:" 
       Font-Name="Verdana" 
       Font-Size="10pt" 
       runat="server"/>

  <p>

  <asp:TextBox id="Text1" 
       runat="server" />

  &nbsp;&nbsp;

  <asp:CustomValidator id="CustomValidator1"
       ControlToValidate="Text1"
       ClientValidationFunction="ClientValidate"
       OnServerValidate="ServerValidation"
       Display="Static"
       ErrorMessage="Not an even number!"
       ForeColor="green"
       Font-Name="verdana" 
       Font-Size="10pt"
       runat="server"/>

  <p>

  <asp:Button id="Button1"
       Text="Validate" 
       OnClick="ValidateBtn_OnClick" 
       runat="server"/>

有关更多信息,请检查自定义验证器

希望我的回答能帮助您解决问题。

于 2011-09-23T20:16:01.493 回答
1

当然,如果您无条件重定向,则该验证将被忽略。你应该this.IsValid在重定向之前打电话

protected btRedirect_Click( object sender, EventArgs e )
{
   if ( this.IsValid )
     Response.Redirect( ... );
}  
于 2011-09-23T20:10:41.340 回答