tisdag 15 januari 2013

ASP.NET - Dynamically and programmatically work with System.Web.UI.WebControls.Content controls

In my current project I had a scenario where I wanted to (sometimes) replace/not show content from my ASP.NET Master Page on a particular ASPX-page. One way to do this is of course to create a new master page, add necessary content to it and then programmatically use different master pages depending on some parameters (in my case a query string). I'm not a big fan of this solution since it introduces more complexity to the project in forms of new files.

A cleaner and better way (my opinion!) would be to, sometimes, replace some of the System.Web.UI.WebControls.ContentPlaceHolder controls from my master page with empty content and by this achieving the same goal as with the multiple master pages approach. The problem with this solution is that is seems impossible to work with existing ASP.NET Content controls from code behind. Even if I set IDs to the controls I can't seem to access them from code. I found a simple solution to this by creating a new, empty ITemplate and using the Page.AddContentTemplate function:

public class StandardPage : Page
{
    protected override void OnPreInit(System.EventArgs e)
    {
        // If the param showStripped is submitted we want to hide 
        // header and footer by adding empty content controls overriding 
        // ContentPlaceholders for those areas in the MasterPage
        var showStripped = Request.Params["showStripped"];
        if (!string.IsNullOrEmpty(showStripped))
        {
            AddContentTemplate("cphFacebookScript", new EmptyContent());
            AddContentTemplate("cphHeader", new EmptyContent());
            AddContentTemplate("cphFooter", new EmptyContent());
        }
        base.OnPreInit(e);
    }
}

public class EmptyContent : ITemplate
{
    void ITemplate.InstantiateIn(Control container) { }
}

So when calling the page with the querystring showStripped we will add empty content templates to some of the content placeholders from the master page. Pretty simple, right?! :)

1 kommentar:

  1. Casino Tycoon | Login, login, make a casino
    Login, make a 성남 출장마사지 casino · Login · Make a casino · Find the best bonus · Make your 문경 출장안마 casino · Choose a one that 메이플 캐릭터 슬롯 you 경주 출장마사지 want to place your bets. 과천 출장안마 · Find the Best

    SvaraRadera