【发布时间】:2011-11-10 15:52:32
【问题描述】:
我需要在页面的每次加载/回发时检查 Page.IsValid 的值,以便执行一些其他逻辑。
但是,如果没有调用 Page.Validate(),则无法调用 IsValid。
如果回发的控件将 CausesValidation 设置为 false,则不会调用 Page.Validate()。
如果我自己调用 Page.Validate(),它会导致页面上的所有验证器都显示出来。
我目前有两个解决这个问题的方法。
第一种方法,我在 IsValid 周围使用 try catch。如果未发生验证,我会捕获将发生的异常。然后我调用 Page.Validate,检查 IsValid 的值,然后遍历所有 Validator 以将它们全部标记为 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,然后重置所有验证器。
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 属性,因为它首先被保持为私有肯定是有某种原因的。
还有其他人有更好的解决方案或想法吗?
【问题讨论】:
-
这是你必须在服务器端做的事情吗?在加载时执行客户端验证可能更容易。
-
@JamesJohnson 我必须在有效/无效上运行的代码必须在服务器端运行,是的。尽管即使它可能是客户端,我也看不出这有什么帮助,因为我仍然需要检查页面是否有效而没有验证器触发/显示。
-
如何使用特定的ValidationGroup,并使用Page.Validate(String) 重载?
-
非常感谢。这对于生产来说可能不是理想的情况,但它确实有助于解决神秘的验证失败。竖起大拇指!更好的解决方案 - 在找出导致问题的原因后处理单独的验证器。
-
将第二种方法的第一行翻译成VB需要一些未经训练的猜测,所以在这里以防万一其他人需要它 Dim t As Type = GetType(Page) If t.GetField( "_validated", System.Reflection.BindingFlags.Instance 或 System.Reflection.BindingFlags.NonPublic).GetValue(Me)
标签: c# asp.net .net validation