Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a user control in a base page class

I have a base page class that inherits from Page. We'll call it SpiffyPage.

I also have a user control called SpiffyControl.

I then have an aspx page, ViewSpiffyStuff.aspx, that inherits from SpiffyPage.

On page load, the SpiffyPage class is supposed to inject a SpiffyControl into the aspx page.

The problem is that SpiffyControl is a user control, and to instantiate that in the code behind one has to access the ASP namespace, sort of like:

ASP.controls_spiffycontrol_aspx MyControl;

But SpiffyPage isn't an aspx page, it's just a base page, and as such I can't access the ASP namespace, and I therefore can't instantiate a SpiffyControl in order to inject it.

How can I achieve my goal?

Edit:

One important point is that I must have a reference to the actual control type so I can assign values to certain custom Properties. That's why a function like LoadControl, which returns type Control, won't work in this case.

like image 907
Pete Michaud Avatar asked May 21 '09 18:05

Pete Michaud


People also ask

Can we use user control in MVC?

In ASP.Net you need to register one tagprefix and then use the user control by tagprefix registered but in ASP.Net MVC using simple Thml. RenderPartial we can use the user control.

How do I add a user control to a SharePoint Webpart?

To create a user control for SharePointOn the menu bar, choose Project > Add New Item. The Add New Item dialog box opens. In the Installed pane, choose the Office/SharePoint node. In the list of SharePoint templates, choose User Control (Farm Solution Only).


1 Answers

Add a baseclass to your SpiffyControl, like:

public class SpiffyBase : UserControl
{
    public void DoIt()
    {
        Response.Write("DoIt");
    }
}

and then you make your SpiffyControl inherit that baseclass, like:

public partial class SpiffyControl : SpiffyBase

then you should be able to do this from a Basepage class:

public class BasePage : Page
{
    protected override void OnLoad(EventArgs e)
    {
        var c = Page.LoadControl("SpiffyControl.ascx") as SpiffyBase;

        Page.Controls.Add(c);

        c.DoIt();
    }
}
like image 164
Johan Leino Avatar answered Sep 22 '22 00:09

Johan Leino