My company's web application projects are heavily based on user controls. One common case is like we want to reuse the UI visual elements but note the packaged original logic .
I have read some very smelly code in some user controls code behinde.
if(WebConfig.CurrentProject == "xxx")
{
//do xxx's logic
ddlPostalCode.DataSouce= this.addressManager.getUSAPostal();
}
else
{
//do yyy's logic
ddlPostalCode.DataSouce= this.addressManager.getUKPostal();
}
//Or use configuration
if(config.enableAlpha)
{
//Do alpha's logic
ddlPostalCode.DataSouce= this.addressManager.getAlphaPostalCode();
}
And these logics normally involving manipulating server controls .
So I am thinking, if we just want to reuse the visual element and parts of its logic. Why don't we make the server and its event handler public ?
//In xxx.ascx.cs
public EventHandler AddressControl_Init;
protected override void OnInit(EventArgs e)
{
if(this.AddressControl_Init!= null)
{
this.AddressControl_Init(sender, e);
}
else
{
//Default logic.
}
}
//In xxx.ascx.designer.cs
public public global::XYZ.Controls.Basic.XYZDropDownList ddlPostalCode;
//In the code behinde of the page using this address ascx.
//HostingPage.aspx.cs
protected override void OnPreInit(EventArgs e)
{
this.AddressControl.AddressControl_Init += new EventHandler(USAAddressControl_Init);
}
void USAAddressControl_Init(object sender, EventArgs e)
{
//Now i can use any business manager class here to populate the source data.
this.AddressControl.ddlPostalCode.DataSource = Anymanager.GetMarsCode();
this.AddressControl.ddlPostalCode.DataBind();
}
This is a very simple example, but it also can be a very flexsiable solution. It decouple the logic behinde the user control. Let the user, the page to deside the control's logic.
Is there any better elegent ways to solve my problem?