【问题标题】:In Asp.Net, how would I determin which validator control has set Page.IsValid to false?在 Asp.Net 中,如何确定哪个验证器控件已将 Page.IsValid 设置为 false?
【发布时间】:2012-07-26 15:04:54
【问题描述】:

我有一个包含许多RequiredFieldValidators 的巨大表单,我如何以编程方式确定哪个控件将PageIsValid 属性设置为false

【问题讨论】:

    标签: asp.net validation postback


    【解决方案1】:

    在服务器端,您可以查看Validators 属性以找到所有IValidator 实例。然后,您只需测试哪些不是.IsValid

    var notValidValidators = Page.Validators.Cast<IValidator>().Where(v => !v.IsValid);
    

    在客户端,它是相似的。有一个 JavaScript 数组 Page_Validators,每个数组都有一个 isvalid 属性。

    var notValidValidators = Page_Validators.filter(function(v) { return !v.isvalid; });
    

    【讨论】:

    • 看起来很有希望,但是:Error 17 'System.Web.UI.ValidatorCollection' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Web.UI.ValidatorCollection' could be found (are you missing a using directive or an assembly reference?)
    • IEnumerable 上的 LINQ 扩展方法在哪里。确保你有一个“使用 System.Linq;”。如果 ValidatorCollection 不支持 IEnumerable,您可以执行 Page.Validators.Cast().Where(...) 之类的操作
    • Page.Validators.Cast&lt;IValidator&gt;().Where(v =&gt; !v.IsValid) 似乎可以编译,谢谢!
    【解决方案2】:

    您可以检查各个验证器的.IsValid 属性。

    如果是RequiredFieldValidator,如果控件仍然无效,用户应该不能回发。你想做什么?

    【讨论】:

    • 他们都有EnableClientScript="false",并且还有一堆以编程方式添加的。我有一个无效的表单实例,但未指定错误,我正在尝试找出哪个验证器正在触发,以便我可以添加更明确的消息。
    • 当然。您可以使用 Mark 的 LINQ 解决方案,因为这似乎是最有效的。我自己对 linq 不太熟悉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2011-09-29
    • 2019-01-05
    • 2023-03-20
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多