views:

2098

answers:

2

Hi,

I have a ASP.NET 2.0 webpage with 2 UserControls (.ascx). Each UserControl contains a bunch of validators. Placing a ValidationSummary on the page will display all validation errors, of both UserControl's. Placing a ValidationSummary in each UserControl will display all the errors of both controls twice.

What I want is a ValidationSummary for each UserControl, displaying only the errors on that UserControl.

I've tried to solve this by setting the ValidationGroup property of the validators on each usercontrol dynamicaly. That way each validationsummary should display only the errors of its UserControl. I've used this code:

foreach (Control ctrl in this.Controls)
{
    if (ctrl is BaseValidator)
    {
        (ctrl as BaseValidator).ValidationGroup = this.ClientID;
    }
}
ValidationSummary1.ValidationGroup = this.ClientID;

This however seems to disable both clientside and server side validation, because no validation occurs when submitting the form.

Help?

+3  A: 

The control that is causing your form submission (i.e. a Button control) has to be a part of the same validation group as any ValidationSummary and *Validator controls.

LostInTangent
+1  A: 

If you use ValidationGroups, the validation only occurs if the control causing the postback is assign to the same ValidationGroup.

If you want to use a single control to postback you can still do this but you would need to explicitly call the Page.Validate method.

Page.Validate(MyValidationGroup1);
Page.Validate(MyValidationGroup2);
if(Page.IsValid)
{
    //do stuff
}

Suggestion: Why don't you expose a public property on your user controls called ValidationGroup? In the setter you could explicitly set the validation group for each validator. You could also use your loop, but it would be more efficient to set each validator explicitly. This might improve the readability of the code using the user controls.

HectorMac