使用PostBackUrl或Response忽略验证.使用c#进行重定向

本文关键字:使用 重定向 验证 PostBackUrl Response | 更新日期: 2023-09-27 18:09:35

我有一个带有一些自定义验证的表单。表单上有一个按钮,它应该把用户带到"确认页面",以显示订单的所有细节。

页面验证
    <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。重定向到buttonclick方法,所有验证控件都将被忽略。

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

我试过设置CausesValidation=False,但没有成功。

有什么建议吗?

使用PostBackUrl或Response忽略验证.使用c#进行重定向

当然,如果无条件重定向,则忽略验证。您应该在重定向之前调用this.IsValid,例如

protected btRedirect_Click( object sender, EventArgs e )
{
   if ( this.IsValid )
     Response.Redirect( ... );
}  

检查此代码

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

更多信息请查看自定义验证器

希望我的回答能帮到你。