Defining ASP.NET Update Panel Template Contents Dynamically

The ASP.NET UpdatePanel was introduced with the ASP.NET 2.0 AJAX Extensions almost a century ago (kidding, but almost feels like it!Winking smile). It allows us to have AJAX-style effects (partial page loads) with very little effort.

The UpdatePanel has a property, ContentTemplate, which is, well, a template, which means it can only be set through markup – not so good for dynamic contents -, or by implementing our own ITemplate class – slightly more work, but this can be reused in other scenarios where an ITemplate is required:

public class Template : Control, ITemplate
{
    public void InstantiateIn(Control container)
    {
        var controls = this.Controls.OfType<Control>().ToList();
 
        for (var i = 0; i < controls.Count; i++)
        {
            var control = controls[i];
            container.Controls.Add(control);
        }
    }
}
 
protected override void OnLoad(EventArgs e)
{
    var tb = new TextBox { ID = "time" };
    var timer = new Timer { Interval = 1000, Enabled = true };
    timer.Tick += timer_Tick;
 
    var tmp = new Template();
    tmp.Controls.Add(tb);
    tmp.Controls.Add(timer);
 
    var up = new UpdatePanel();
    up.ContentTemplate = tmp;
 
    this.Form.Controls.Add(up);
 
    base.OnLoad(e);
}
 
void timer_Tick(object sender, EventArgs e)
{
    var time = (sender as Control).NamingContainer.FindControl("time") as TextBox;
    time.Text = DateTime.Now.ToString();
}

There is also a property, ContentTemplateContainer, which is a control to which you can add your controls, so that they are added to the UpdatePanel. This is exactly what we need:

protected override OnLoad(EventArgs e)
{
    var tb = new TextBox { ID = "time" };
    var timer = new Timer { Interval = 1000, Enabled = true };
    timer.Tick += this.timer_Tick;
    
    var up = new UpdatePanel();
    up.ContentTemplateContainer.Controls.Add(tb);
    up.ContentTemplateContainer.Controls.Add(timer);
    
    this.Form.Controls.Add(up);
    
    base.OnLoad(e);
}

                             

3 Comments

  • I am happy to used ASP so ASP help for my work become better

  • Very much appreciated, thanks :-)

  • For the user experience, Update panel control allows us to use the AJAX-style effects in ASP.NET. By the help of <a href=”http://www.sagacademy.com/dotnet-development-training-jaipur”>best .NET development training course</a>, user can learn how to use ITemplate to make attractive website on DOT NET.

Add a Comment

As it will appear on the website

Not displayed

Your website