tags:

views:

200

answers:

3

I have a number of user controls. The user controls can be used on different pages. The behavior of the user controls are different based on what page they are used on.

How can I set a parameter on the host page that ALL user controls have access to?

+1  A: 

Your description "The behavior of the user controls are different based on what page they are used on" indicates a design flaw. The Control Model in ASP.NET is designed around encapsulation and OOP, which means a control should be agnostic regarding its surrounding context. You should rethink your design with that in mind.

That having been said, it is entirely possible (warning - bad practice) to set a public property on your page that the controls can read:

class MyPage : Page
{
    public string MyProperty;
}

class MyUserControl : UserControl
{
    void Page_Load(object sender, EventArgs e)
    {
        ((MyPage)this.Page).MyProperty //casts Page as the specific page
    }
}
Rex M
A: 

I agree with Rex, I am suspicious of the requirement.

That said, I find it cleaner to put it on the HttpContext.Current.Items collection. The page would set the value preferably on its OnInit, using a nice class wrapping around it, to get the info.

If you want you can have the wrapper actually read the current Url, or check the type of the page (which is the usually the current Handler HttpContext.Current.Handler / don't recall if ajax affects that), which can get you a solution that doesn't needs the page to set anything at all.

eglasius
A: 

As Rex M mentioned, this is bad practice for multiple reasons. If I found that I needed to reference the parent page from the control, I would pass a reference to the page into the control, instead of having the control reference the parent.

I might consider making an interface that all of these pages might implement and pass that into the control. The interface would guarantee the type safety. If you started using this control on a new page that page would need to implement the interface before you could use it with the control. This would help with occasions where you throw the control on a new page and forget that the control has this relationship with the parent (this relationship can be fragile, which is one of the reasons that it is a no no).

Jim Petkus