简体   繁体   中英

OnServerValidate Won't work with PostBackUrl in ASP.Net C#

I'm validating a form using a CustomValidator so I can colour the background of the textbox.

The code behind for the CustomValidator doesn't get called when I click the form's linkbutton. However, when I remove PostBackUrl="orderconfirm.aspx" the code does get called and works fine.

aspx page:

<asp:TextBox ID="txtBillingLastName" Name="txtBillingLastName" runat="server">/asp:TextBox>

<asp:CustomValidator 
     ID="CustomValidatorLN" runat="server" 
     ControlToValidate="txtBillingLastName"  
     OnServerValidate="CustomValidatorLN_ServerValidate"
     ValidateEmptyText="True">
</asp:CustomValidator>
<asp:LinkButton 
     ID="OrderButton" runat="server" 
     PostBackUrl="orderconfirm.aspx" 
     onclick="OrderButton_Click">&nbsp;
</asp:LinkButton>

code behind:

protected void CustomValidatorLN_ServerValidate(object sender, ServerValidateEventArgs args)
    {
        bool is_valid = txtBillingLastName.Text != "";
        txtBillingLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
        args.IsValid = is_valid;
    }

I'm pretty new to .net/c# and to be honest I didn't get the answers to similar problems searched for on here.

Any help would be greatly appreciated.

Server side code runs when the page is requested, It doesn't work because you are posting back to(ie requesting) a different page, so the code never runs. You could post back to the original page then redirect in the code behind but the easiest solution is probably to eliminate orderconfirm.aspx entirely and just do everything in the original page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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