Andrej K
Andrej K

Reputation: 2041

Best way to pass control to parent/base class in ASP.NET

I have an abstract BasePage class that each Page class inherits from. Apart from core functionality I'd like BasePage to cover repetitive tasks that almost all derived classes implement. To do this however the BasePage class would have to hold reference to controls (dropdownlist, gridview, menu...) which are defined in derived class.

My question is what is the best way to pass control reference defined in derived Page class to parent class?

None of the following really gives "best" solution:

  1. Base page to declare variable with name that is the same as control's Id on derived class. This forces the ASP.NET designer not to re-create the control on derived class. (I don't like this since derived class is forced to know and use hard-coded name)

  2. Create abstract property and force derived class to return control reference (CON: In some cases derived class might not include such control)

  3. Pass the control as function call parameter (CON: still requires repetitive code of function call. Function itself then doesn't even have to be on BasePage)

Upvotes: 5

Views: 1883

Answers (1)

nunespascal
nunespascal

Reputation: 17724

A more object oriented approach would be to extend the control classes (dropdownlist, gridview, menu...) and add methods for your repetitive tasks.

If you must define the controls in your BasePage, then you could create a virtual property for these in BasePage. Any derived page that wants to use it would override this and provide the required control.

public class BasePage : System.Web.UI.Page
{
    protected virtual DropDownList MyDropDown { get; set; }

    protected void PopulateList()
    {
        if (MyDropDown != null)
            MyDropDown.Items.Add("option");
    }
}

public partial class MyPage : BasePage
{
    protected override DropDownList MyDropDown
    {
        get
        {
            return DerivedClassList;
        }
        set
        {
            base.DerivedClassList = value;
        }
    }
}

Upvotes: 3

Related Questions