【问题标题】:Custom Control referenced by 'RequiredFieldValidator' cannot be validated无法验证“RequiredFieldValidator”引用的自定义控件
【发布时间】:2011-05-12 11:16:18
【问题描述】:

问题:如何正确扩展自定义控件以使用RequiredFieldValidator?我读过this,但尝试实现它并没有为我解决问题。 到目前为止,这是我想出的:

 <%@ Register src="DynamicGenerator/Controls/ReferenceControl.ascx" tagname="ReferenceControl" tagprefix="uc1" %>
    <uc1:ReferenceControl ID="SelectAgreement" runat="server" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator" ControlToValidate="SelectAgreement" runat="server" ErrorMessage="Select an agreement!"></asp:RequiredFieldValidator>

后面的代码:

[ValidationProperty("ConceptDefinitionId")]
public partial class ReferenceSelector : System.Web.UI.UserControl, IReference
{
   //lots of other stuff
 public string ConceptDefinitionId
        {
            get { return ReferenceControl.ConceptDefinitionId ?? ""; }
            set { ReferenceControl.ConceptDefinitionId = value; }
        }
}

加载此页面给我以下错误:

“RequiredFieldValidator”的 ControlToValidate 属性引用的控件“SelectAgreement”无法验证。

堆栈跟踪:

[HttpException (0x80004005): Control 'SelectAgreement' referenced by the ControlToValidate property of 'RequiredFieldValidator' cannot be validated.]
   System.Web.UI.WebControls.BaseValidator.CheckControlValidationProperty(String name, String propertyName) +8739685
   System.Web.UI.WebControls.BaseValidator.ControlPropertiesValid() +40
   System.Web.UI.WebControls.BaseValidator.get_PropertiesValid() +21
   System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +27
   System.Web.UI.Control.PreRenderRecursiveInternal() +80
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842

【问题讨论】:

  • 您的代码对我来说是正确的。我遇到了同样的问题,除了我错过了ValidationPropertyAttribute。一旦我添加了(我的属性是只读的,并返回int,用于比较),它就按预期工作了。

标签: c# asp.net custom-controls requiredfieldvalidator validation-controls


【解决方案1】:

您需要将 RequiredFieldValidator 放在 UserControl 中并验证特定控件,例如 TextBoxDropDown,因为仅允许在同一命名容器中使用验证器,而在您的情况下,UserControl 是不同的容器所以这行不通。

另一种方法是使用ValidationPropertyAttribute

【讨论】:

  • 我已经在使用 ValidationPropertyAttribute(参见后面的代码),但我想我用错了?
  • 尝试更改EnableClientScript 属性
  • 尝试在 RequiredFieldEditor 上设置它的真假,但没有结果。
  • 如果您想验证您的自定义 UserControl 的两个实例,您不能(通常)通过将验证器放在 UserControl 中来实现。在这种情况下,最好的解决方案是使用ValidationPropertyAttribute。您指定的自定义控件的任何属性都将通过.ToString() 传递给验证器。 (我的属性是只读的int。)
猜你喜欢
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
相关资源
最近更新 更多