Thursday, March 22, 2012

Why this can not work?

Here I have a radiobuttonlist named SelectionList, and I want to do some selective validation like this: Only when SelectionList.SelectedIndex = 1 can all the IValidator in Page.Validators be actived. The code is as follows:
switch(SelectionList.SelectedIndex)
{
case 0:
BlahBlahBlah...
break;
case 1:
foreach(IValidator val in Page.Validators)
{
val.Validate();
}
if(Page.IsValid)
BlahBlahBlah...;
break;
}
But the problem is that all the IValidator in this page are always enabled no matter what the SelectionList.SelectedIndex is, and the situation is the same when I use If-Else structure.
So can anyone help me about this? Thanks!The point is ASP.NET validates the form using the validators before the page is actually loaded (init phase). THis behavior is by design and is desired in 99% of the cases. If you want to do something like what you're suggesting, you can do this:
- disable the validators and enable them in your code before validation (I don't recommend this, never tried myself)
- use a customvalidator to put the switch statement in. It's better not to do magic things with validators but let ASP.NET do all the work (I never call the Validate method myself).

Does this help?

0 comments:

Post a Comment