为什么这个附加事件不会触发?

时间:2010-11-15 07:59:04

标签: asp.net .net-3.5

那里!

我正在使用简单的服务器控制:

public sealed class FooControl : CompositeControl
{
    public string ValidationGroup
    {
        get
        {
            this.EnsureChildControls();
            return this._fooValidator.ValidationGroup;
        }
        set
        {
            this.EnsureChildControls();
            this._fooValidator.ValidationGroup = value;
        }
    }

    private readonly CustomValidator _fooValidator = new CustomValidator
    {
        ID = "foo",
        Display = ValidatorDisplay.None,
        EnableClientScript = false,
        Enabled = true,
        ErrorMessage = "FooErrorMessage",
        SetFocusOnError = true
    };

    protected override void CreateChildControls()
    {
        this.Controls.Add(this._fooValidator);

        this._fooValidator.ServerValidate += ValidateFoo;
    }

    protected static void ValidateFoo(object source, ServerValidateEventArgs args)
    {
        args.IsValid = false;
    }
}

现在我正在调用验证,如

public partial class MyFooPage : Page
{
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        // FooControl was added @ OnLoad
        // ValidationGroup of FooControl remains empty
        // this.GetValidators() returns the fooValidator of FooControl
        this.Validate();
    }
}

但页面仍然有效,并且customValidator无效。

我深入挖掘了一下:

页面的.Validate() - 方法,在每个验证程序上调用.Validate(),内部调用EvaluateIsValid()的{​​{1}}:

CustomValidator

(c)由microsoft

然后调用protected override bool EvaluateIsValid() { string controlValidationValue = string.Empty; string controlToValidate = base.ControlToValidate; if (controlToValidate.Length > 0) { controlValidationValue = base.GetControlValidationValue(controlToValidate); if (((controlValidationValue == null) || (controlValidationValue.Trim().Length == 0)) && !this.ValidateEmptyText) { return true; } } return this.OnServerValidate(controlValidationValue); } 的{​​{1}}:

OnServerValidate

(c)由microsoft

根据调试器,CustomValidator包含一个事件(我附加的验证方法),但不知怎的,它不会被解雇...... ?? !!我还尝试在protected virtual bool OnServerValidate(string value) { ServerValidateEventHandler handler = (ServerValidateEventHandler) base.Events[EventServerValidate]; ServerValidateEventArgs args = new ServerValidateEventArgs(value, true); if (handler != null) { handler(this, args); return args.IsValid; } return true; } - 方法中设置一个断点,它实际上没有被击中。

谁能告诉我为什么,我怎么能让这个工作,我做错了什么?

1 个答案:

答案 0 :(得分:0)

解决方案

public void Validate()
{
  this.IsValid = true;
  if (this.Visible && this.Enabled)
  {
    this.propertiesChecked = false;
    if (this.PropertiesValid)
    {
      this.IsValid = this.EvaluateIsValid();
      if ((!this.IsValid && (this.Page != null)) && this.SetFocusOnError)
      {
        this.Page.SetValidatorInvalidControlFocus(this.ControlToValidate);
      }
    }
  }
}

(c)由microsoft

这是Validate的{​​{1}}方法。

如果

  • 验证者的父级不可见(将BaseValidator设置为Display
  • 验证程序不可见(None设置为不 - Display

None - 标志不会被评估。