I am putting together a website that grabs content from a database and fills it into a component which is then loaded onto the page. The catch is that there are many different components which are unknown at compile time and I want to call them from the database.
For example, there may be several components such as:
- modContent.ascx
- modSlidingBanner.ascx
- modEmailSlug.ascx
and the database will contain a table with fields defining the module to use and the content to load into it:
- ModuleName: "modContent"
- Content: "zippidy doo da"
So let's say modContent.ascx looks like:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="modContent.ascx.cs" Inherits="modContent" %>
<div class="content">
<div class="content-wrapper" ID="divContentWrapper" runat="server">
<asp:Literal ID="litContent" runat="server"></asp:Literal>
</div>
</div>
And modContent.ascx.cs contains the method:
public void FillIn(string html)
{
litContent.Text = html;
}
And on my main page, I want to load this control and call the FillIn method. I can do this easily if I know the control type in advance:
modContent c = LoadControl("~/modContent.aspx");
c.FillIn(ContentFromDatabase);
divTargetPanel.Controls.Add(c);
However, as I mentioned, I want to select one of several Controls based on a string in the database. I can guarantee that each of these Controls will have the FillIn method. And I would like to avoid having to have a large switch clause or something where I have to change code on the main page each time I add a new Control that might be used.
I can get a module loaded onto the page like this:
Control c = LoadControl("~/" + ControlNameFromDatabase + ".aspx");
divTargetPanel.Controls.Add(c);
But cannot call the FillIn method on this control.
I can move the FillIn method functionality to the constructor for the Control and try this:
Assembly assembly = typeof(ControlsParentClass).Assembly;
Type type = assembly.GetType(ControlNameFromDatabase);
skinHome.divContentPanel.Controls.Add(LoadControl(type, new object[] { ContentFromDatabase }));
But, this errors out because litContent
returns null
in modContent.ascx.cs as described in this guy's question.
Obviously the control described above is very simple. I've stripped it down to the basics. The modules will actually be much more complex, each with their own structure and code, but with identical method names/arguments.
Am I going about this a completely wrong way?