简体   繁体   English

OnServerValidate在ASP.Net C#中无法与PostBackUrl一起使用

[英]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. 我正在使用CustomValidator验证表单,因此可以为文本框的背景着色。

The code behind for the CustomValidator doesn't get called when I click the form's linkbutton. 单击表单的链接按钮时,不会调用CustomValidator后面的代码。 However, when I remove PostBackUrl="orderconfirm.aspx" the code does get called and works fine. 但是,当我删除PostBackUrl =“ orderconfirm.aspx”时,代码确实会被调用并正常工作。

aspx page: aspx页面:

<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. 我是.net / c#的新手,老实说,我没有在这里找到类似问题的答案。

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. 您可以将其发布回原始页面,然后在后面的代码中重定向,但是最简单的解决方案可能是完全消除orderconfirm.aspx,然后在原始页面中进行所有操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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