如何动态设置ValidationGroup

[英]How can I set the ValidationGroup dynamically


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.

我有一个带有2个UserControls(.ascx)的ASP.NET 2.0网页。每个UserControl都包含一堆验证器。在页面上放置ValidationSummary将显示UserControl的所有验证错误。在每个UserControl中放置ValidationSummary将两次显示两个控件的所有错误。

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

我想要的是每个UserControl的ValidationSummary,只显示该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:

我试图通过动态设置每个usercontrol上的验证器的ValidationGroup属性来解决这个问题。这样每个validationsummary都应该只显示其UserControl的错误。我用过这段代码:

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?

2 个解决方案

#1


2  

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

如果使用ValidationGroups,则仅在导致回发的控件分配给同一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方法。

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.

建议:为什么不在名为ValidationGroup的用户控件上公开公共属性?在setter中,您可以为每个验证器显式设置验证组。您也可以使用循环,但显式设置每个验证器会更有效。这可能会提高使用用户控件的代码的可读性。

#2


4  

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.

导致表单提交的控件(即Button控件)必须是与任何ValidationSummary和* Validator控件相同的验证组的一部分。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2008/09/26/1badac09b60123d40cdca616cdeb0ea1.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com