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

前端之家收集整理的这篇文章主要介绍了c# – 即使CausesValidation为false,也检查页面是否为IsValid前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在页面的每个加载/回发上检查Page.IsValid的值,以便执行其他一些逻辑.

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

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

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

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

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

  1. bool isValid = false;
  2.  
  3. try
  4. {
  5. isValid = this.IsValid;
  6. }
  7. catch (System.Web.HttpException exception)
  8. {
  9. 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.")
  10. {
  11. //Validation has NOT occurred so run it here,store the result,then set all the validators to valid.
  12. this.Validate();
  13. isValid = this.IsValid;
  14.  
  15. foreach (IValidator validator in this.Validators)
  16. {
  17. validator.IsValid = true;
  18. }
  19. }
  20. }

第二种方法是使用反射从底层页面本身获取字段_validated.然后,如果页面尚未经过验证,则调用Validate时的第一个方法也是如此,然后重置所有Validators.

  1. bool isValidated = (bool)typeof(Page).GetField("_validated",System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(this);
  2.  
  3. bool isValid = false;
  4.  
  5. if (isValidated)
  6. {
  7. isValid = this.IsValid;
  8. }
  9. else
  10. {
  11. this.Validate();
  12. isValid = this.IsValid;
  13.  
  14. foreach (IValidator validator in this.Validators)
  15. {
  16. validator.IsValid = true;
  17. }
  18. }

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

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

解决方法

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

这样,你就可以打电话了

  1. if (this.Page.IsValid)

在你的代码中.

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

  1. Page.Validate("ValidationGroupName")

看看这些examples of group validation

猜你在找的C#相关文章