views:

207

answers:

2

I have a custom control which includes a property of the following definition:

[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate Template { 
  get { return template; }
  set { template = value; }
}

The control overrides CreateChildControls(), and adds several HtmlGenericControls and an asp:Panel control.

The actual actual implementation of the control looks something like this:

<user:Frame runat="server">
   <Template>
      <asp:Literal runat="server" ID="SomeControl" Text="SomeValue" />     
   </Template>
</user:Frame>

While the page renders as intended, it has a number of consequences of varying severity, including:

  • Controls enclosed within the Template cannot be referenced directly, and FindControl is required. This is fine.
  • I've been unable to use validation controls on them.

Is there a better way to design my custom control? Or perhaps just a way to get validation working?

+1  A: 

By default the framework assumes that you may have more than one template in a control, like say in a Repeater. In your case you have to tell it that you intend to have a single template by using the TemplateInstance property. E.g.

[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Template { 
  get { return template; }
  set { template = value; }
}

This will allow you to reference the templated controls directly, and should fix your validation problems as well.

codemonkeh
+1  A: 

One way to get validation to work in this case is to add the validation controls programatically. For example:

var c = parentControl.FindControl("id");

parentControl.Controls.AddAt(
   parentControl.Controls.IndexOf(c) + 1,
   new RequiredFieldValidator() { ControlToValidate = c.D });
eulerfx