she swears <i>geek</i> is a term of endearment

Adding child content to ascx controls

For some reason, I still struggle with creating declarative controls in asp.net that can have child controls between their tags.  Custom controls are the correct solution but what about all those cases where you have some ascx markup and you want to place the output of embedded controls inside a placeholder, for example?

I just hacked a simple answer to this problem and thought I’d share for your critique.

 

This happens to be an MVC ViewUserControl but it should work for any ascx Control

 

Heres the ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ChildRenderer.ascx.cs" Inherits="MvcTestApp.Views.ChildRenderer" %>
I am the top stuff
<div>
<asp:PlaceHolder ID="ChildContent" runat="server"></asp:PlaceHolder>
</div>
I am the bottom
<div runat="server" id="endMarker" />

 

And the ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
 
namespace MvcTestApp.Views
{
 
   
 
    [ParseChildren( false )] 
    public partial class ChildRenderer : System.Web.Mvc.ViewUserControl
    {
 
        private bool _endOfAscxParse = false;
 
        protected override void AddParsedSubObject( object obj )
        {
            /*if( obj is System.Web.UI.Control )
            {
                this.ChildContent.Controls.Add( obj as System.Web.UI.Control );
            }
            else
            {
                base.AddParsedSubObject( obj );
            }*/
            if( obj is Control && ( obj as Control ).ID == "endMarker" )
            {
                _endOfAscxParse = true;
                return;
            }
            if( _endOfAscxParse )
            {
                this.ChildContent.Controls.Add( obj as Control );
            }
            else
            {
                base.AddParsedSubObject( obj );
            }
        }
    }
}

 

Now, when the last div is parsed, it sets a flag and all additional content is placed inside the placeholder.

It works.  Its a little nasty?  Ok.  But it works!

One Response to “Adding child content to ascx controls”

  1. […] Nothing like self-correction.  Following up on this post […]

Leave a Reply