即使CausesValidation为false,也检查页面是否为IsValid

Rob*_*Day 6 .net c# asp.net validation

我需要在页面的每个加载/回发上检查Page.IsValid的值,以便执行其他一些逻辑.

但是,如果未调用Page.Validate(),则无法调用IsValid.

如果回发的控件将CausesValidation设置为false,则不会调用Page.Validate().

如果我自己调用Page.Validate(),则会导致页面上的所有Validators显示.

我目前有两个解决这个问题的方法.

第一种方法,我在IsValid周围使用try catch.我捕获了如果未进行验证将发生的异常.然后我调用Page.Validate,检查IsValid的值,然后循环遍历所有Validators,将它们全部标记为Valid,这样它们就不会显示在页面上.

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.")
    {
        //Validation has NOT occurred so run it here, store the result, then set all the validators to valid.
        this.Validate();
        isValid = this.IsValid;

        foreach (IValidator validator in this.Validators)
        {
            validator.IsValid = true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种方法是使用反射从底层页面本身获取字段_validated.然后,如果页面尚未经过验证,则调用Validate时的第一个方法也是如此,然后重置所有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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢这两个解决方案,因为我不喜欢异常编码,我不喜欢使用反射来获取Validated属性,因为必须有一些原因它首先保持私有.

有没有其他人有更好的解决方案或任何想法?

Fab*_*iro 9

我建议您只使用验证器,并将EnableClientScript选项设置为false.

这样,你就可以打电话了

if (this.Page.IsValid)
Run Code Online (Sandbox Code Playgroud)

在你的代码中.

如果要验证特定验证组,只需在服务器端使用此行:

Page.Validate("ValidationGroupName")
Run Code Online (Sandbox Code Playgroud)

看看这些组验证的例子