我如何设置的ValidationGroup动态 [英] How can I set the ValidationGroup dynamically

查看:205
本文介绍了我如何设置的ValidationGroup动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET 2.0的网页与用户控件2(的.ascx)。每个用户控件包含一串验证程序。在页面上放置的ValidationSummary将显示所有验证错误都UserControl的的。在每个用户控件放置的ValidationSummary会显示这两个控件的所有错误的两倍。

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.

我要的是每个用户控件一个的ValidationSummary,显示仅在用户控件中的错误。

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

我试着通过设置验证的ValidationGroup属性上的每个用户控件dynamicaly来解决这个问题。这样,每一个的ValidationSummary应该只显示其用户控件的错误。我用这个code:

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.

帮助?

推荐答案

如果您使用ValidationGroups,验证只发生,如果造成回发的控制分配到相同的ValidationGroup。

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

如果你想使用一个单一的控制回发你仍然可以做到这一点,但你需要显式调用Page.Validate方法。

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
}

建议:
你为什么不叫暴露在的ValidationGroup您的用户控件的公共属性?
在二传,你可以明确地设置验证组每个校验。你也可以使用你的循环,但它会更有效地明确设定每个校验。这可能使用用户控件提高code的可读性。

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动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆