加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:34:20 所属栏目:百科 来源:网络整理
导读:我需要在页面的每个加载/回发上检查Page.IsValid的值,以便执行其他一些逻辑. 但是,如果未调用Page.Validate(),则无法调用IsValid. 如果回发的控件将CausesValidation设置为false,则不会调用Page.Validate(). 如果我自己调用Page.Validate(),则会导致页面上的
我需要在页面的每个加载/回发上检查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;
        }
    }
}

第二种方法是使用反射从底层页面本身获取字段_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;
    }
}

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

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

解决方法

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

这样,你就可以打电话了

if (this.Page.IsValid)

在你的代码中.

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

Page.Validate("ValidationGroupName")

看看这些examples of group validation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读