views:

1094

answers:

4

ASP.NET master pages - essential things.

However, I have a lot of very similar UserControls in my projects - it might be a standard layout for an AJAX ModalPopup, or something more involved.

I wish I could get rid of some of my duplicated code (both in ascx files and code-behind) with some Master UserControls.

Does anyone have any suggestions of a way to achieve this?

A: 

Inheritance. You build the base control as a base class, and then inherit from it.

Joel Coehoorn
I have done this for the code-behind side of things (i.e. my UserControl.ascx.cs file inherits from my BaseUserControl rather than System.Web.UI.UserControl.However, this does help me in terms of adding standard HTML and server controls to my base control.
Richard Ev
A: 

You could also place nested user control on a place holder control in a "master" user control. Use Load method that accepts virtual path to ascx file to load appropriate control.

Aleksandar
+1  A: 

The closest thing I can suggest for what you are looking for is a templated custom control. Unfortunately, sharing controls across projects is a lot easier if those things are custom controls, without an ascx file.

Chris Shaffer
+1  A: 

I managed to get this to work using the following code:

public class MasterLoader : UserControl
{
    MasterUserControl _masterUserControl;

    protected override void CreateChildControls()
    {
        Controls.Clear();
        base.CreateChildControls();

        Controls.Add(MasterControl);
    }

    protected override void AddedControl(Control control, int index)
    {
        if (control is MasterUserControl)
            base.AddedControl(control, index);
        else
            MasterControl.ContentArea.Controls.Add(control);
    }

    private MasterUserControl MasterControl
    {
        get
        {
            if (_masterUserControl== null)
                _masterUserControl= (MasterUserControl)LoadControl("~/MasterUserControl.ascx");

            return _masterUserControl;
        }
    }
}

Child user controls inherit from the MasterLoader class. The master user control included a placeholder control that I exposed as a public property called ContentArea.

public partial class MasterUserControl: UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public PlaceHolder ContentArea 
    {
        get
        {
            return phContent;
        }
    }
}

Event binding and view state work as expected without any changes to any of the user controls.

Mike