I need to check the Page.IsValid value on every load / back of the page to execute some other logic.
However, IsValid cannot be called unless Page.Validate () is called.
Page.Validate () will not be called if the control that was sent back has a CausesValidation of false.
If I call Page.Validate () myself, it causes the display of all indicators on the page.
I currently have two solutions to this problem.
The first method, I use try catch around IsValid. I will catch an exception that will happen if the check did not happen. Then I call up the page. Validate checks the value of IsValid, then iterates over all the checks to mark them as Valid so that they do not appear on the page.
bool isValid = false;
try
{
isValid = this.IsValid;
}
catch (System.Web.HttpException exception)
{
if(exception.Message == "Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.")
{
this.Validate();
isValid = this.IsValid;
foreach (IValidator validator in this.Validators)
{
validator.IsValid = true;
}
}
}
The second method is to use reflection to get the _validated field from the main page itself. Then I do the same as the first method when I call "Check", if the page has not been checked, and then again reset all validators.
bool isValidated = (bool)typeof(Page).GetField("_validated", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(this);
bool isValid = false;
if (isValidated)
{
isValid = this.IsValid;
}
else
{
this.Validate();
isValid = this.IsValid;
foreach (IValidator validator in this.Validators)
{
validator.IsValid = true;
}
}
I don’t like any of these solutions, because I don’t like coding with exceptions, and I don’t like using reflection to get the Validated property, because, apparently, for some reason it was closed in the first place.
Does anyone have any better solutions or ideas?