Search code examples
asp.netuser-controlsboilerplate

ASP.NET: User control with access to the controls that it wraps


I have a bunch of occurrences of this kind of boilerplate code in my ASP.NET project.

<div class="inputfield">
  <div class="tl">
    <span class="tr"><!-- --></span>
    <span class="ll"><!-- --></span>
    <div class="lr">
      <div class="cntnt">
        <asp:TextBox .../>
      </div>
    </div>
  </div>
</div>

As you may have guessed, everything in that snippet is pure boilerplate except for the innermost text field.

What is the best way to avoid such boilerplate in ASP.NET? In e.g. Django I would make a custom tag for it, as such:

{% boiler %}
<input ... />
{% endboiler %}

I was thinking that maybe I can create a user control, but all the tutorials on ASP.NET user controls that I've found are very simplistic and "self-closing", i.e. they are not aware of the contents of the tag. I need something along the lines of:

<Hello:MyControl>
  <asp:TextBox .../>
</Hello>

So my question is the following: what's the best way to avoid the boilerplate?


Solution

  • You can use an ITemplate property. Thus, you can inject different content in different situations.

    [PersistChildren(false), ParseChildren(true, "ContentTemplate")]
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
    
        [System.ComponentModel.Browsable(false), System.Web.UI.PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate ContentTemplate { get; set; }
    
        protected override void CreateChildControls()
        {
            if (this.ContentTemplate != null)
                this.ContentTemplate.InstantiateIn(this);
    
            base.CreateChildControls();
        }
    }