【问题标题】:How to get the validator's controltovalidate attribute in ASP.NET codebehind?如何在 ASP.NET 代码隐藏中获取验证器的 controltovalidate 属性?
【发布时间】:2016-07-11 20:24:56
【问题描述】:

在页面的代码隐藏中,我创建了一个错误列表,而不是使用样式有限的验证摘要。

这是我用于此的代码:

Panel_feedback.Controls.Add(new LiteralControl("<div class='alert alert-danger alert-dismissible fade in' role='alert'>"));
Panel_feedback.Controls.Add(new LiteralControl("<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button>"));
Panel_feedback.Controls.Add(new LiteralControl("<h2>ERROR!</h2>"));
Panel_feedback.Controls.Add(new LiteralControl("<ul class='fa-ul'>"));

foreach (IValidator error in this.Validators)
  {
     if (!error.IsValid)
         Panel_feedback.Controls.Add(new LiteralControl("<li><i class='fa-li fa fa-times-circle'></i>" + error.ErrorMessage + "</li>"));
   }
Panel_feedback.Controls.Add(new LiteralControl("</ul>"));

似乎错误对象应该具有“controltovalidate”之类的属性,但事实并非如此。我想知道 controltovalidate 目标的原因是因为我想将边框更改为红色,以便用户看到哪个文本框是错误的。

这是我的一个验证器的示例:

<asp:RequiredFieldValidator ID="RequiredFieldValidator_name" runat="server" ErrorMessage="Vul uw naam in" Display="none" ControlToValidate="TextBox_name"></asp:RequiredFieldValidator>

提前致谢

【问题讨论】:

    标签: c# asp.net validation


    【解决方案1】:

    尝试转换为 BaseValidator 而不是 IValidator,这应该有更多详细信息以满足您的需求。

    MSDN documentation

    foreach (BaseValidator error in this.Validators)
    {
        if (error.IsValid)
            continue;
    
        Panel_feedback.Controls.Add(new LiteralControl("<li><i class='fa-li fa fa-times-circle'></i>" + error.ErrorMessage + "</li>"));
        string failedControlID = error.ControlToValidate;
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2011-04-07
      • 2011-05-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多