Thursday, March 26, 2009

C# How To: Create a simple "module" framework using ASCX UserControls

The concept is pretty basic, I simply want to re-use various ASCX user controls I've created within various ASPX Webforms that also happen to use MasterPages. I also want to handle error messages through a lable on the Webform. Another advantage of this is that you can organize your UI into a bunch of usercontrol files within a folder structure. It's not a groundbreaking design pattern, but works nicely for many small projects.

So, the end goal is to be able to pass a querystring to determine which control to load within the page. The URL would look like this: domain.com/Default.aspx?mod=grid

So, there are 4 items you need to create for my example: (in this order)
- /MasterPage.master (Master Page)
- /default.aspx (Webform)
- /default.aspx.cs (Webform codefile)
- /Modules (folder)
- /Modules/grid.ascx (UserControl)

Here's my default.aspx code:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" CodeFile="Default.aspx.cs" Inherits="Default" %><asp:content id="Content1" runat="Server" contentplaceholderid="ContentPlaceHolder1"><asp:label id="ErrMsgLbl" runat="server"></asp:label></asp:content>

My Default.aspx.cs code:
public partial class Default : System.Web.UI.Page
{
string ModuleName = "";
protected void Page_Init(object sender, EventArgs e)
{
if (Request.QueryString["mod"] != null)
{
ModuleName = Request.QueryString["Mod"].ToString();
ContentPlaceHolder cph = this.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;

try
{
UserControl usercontrol = this.LoadControl("~/Modules/" + ModuleName + ".ascx") as UserControl;
cph.Controls.Add(usercontrol);
}
catch (Exception ex){ErrMsgLbl.Text = ex.Message;}
}
}
My Grid.ascx code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Grid.ascx.cs" Inherits="Modules_Grid" EnableViewState="False" %>...your controls go here...


Cheers!

No comments: