Imagine you're setting up a cross-page call. What if the original page contains validators? Imagine a page with a text box whose value is to be posted to another page. You don’t want the post to occur if the text box is empty. To obtain this, you add a RequiredFieldValidator control and bind it to the text box.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="Validator1" runat="server"
ControlToValidate="TextBox1" Text="*" />
<asp:Button ID="Button1" runat="server" Text="Apply request..."
OnClick="Button1_Click" PostBackUrl="targetpage.aspx" />
As expected, when you click the button the page won’t post if the text box is empty; and a red asterisk (plus an optional message) is displayed to remark the error. This is because by default button controls validate the input controls before proceeding with the post. Is that all or is there more to dig out?
In most cases, the RequiredFieldValidator benefits of the client-side capabilities of the browser. This means that in case of empty text boxes the button doesn’t even attempt to make the post. Let’s try with a CustomValidator control which instead requires that some server-side code is run to check the condition. Can you spot the scenario? You’re on, say, post.aspx and want to reach target.aspx; to make sure you post only under valid conditions, though, you first need a trip to post.aspx to perform some validation. Add this control, write the server validation handler and put a breakpoint in its code.
<asp:CustomValidator ID="CustomValidator1" runat="server" Text="*"
ControlToValidate="TextBox1" OnServerValidate="ServerValidate" />
Debugging this sample page reveals that posting to another page is two-step operation. First a classic postback is made to run any server-side code registered with the original page (for example, server-side validation code or code associated with the click of the button). Next, the cross-page call is made to reach the desired page.
void ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
if (String.Equals(args.Value, "Dino"))
args.IsValid = true;
}
The preceding code sets the page’s IsValid property to false if the text box contains other than Dino. However, this fact alone doesn’t prevent the transition to the target page. In other words, you could have invalid input data posted to the target page.
Fortunately, this issue finds an easy workaround, as below.
if (!PreviousPage.IsValid)
{
Response.Write("Sorry, the original page contains invalid input.");
Response.End();
return;
}
In the target page, you test the IsValid property on the PreviousPage property and terminates the request in case of a negative answer.