Let say your web application needs to provide different user interface to different user groups. Or, you want to add additional modules without need to re-deploy complete application. In both example cases, one of the ways to achieve this is by loading of user controls dynamically.
Create a new project with one web page and add PlaceHolder control to web form. Markup code of web page could look like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DefaultCS.aspx.cs" Inherits="DefaultCS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="phModule" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Now add one web user control to project and name it "MyUserControl.ascx". Add some content to user control. This code example contains one Label control with welcome message:
<%@ Control Language="VB" AutoEventWireup="true" CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Hello, this is My User Control dynamically loaded :)"></asp:Label>
Now, you can write ASP.NET server side code to web page, to dynamically load web user control. Code could look like this:
// We need this namespace to load controls dynamically
using System.Web.UI;
public partial class DefaultCS : System.Web.UI.Page
{
protected void Page_Init(object sender, System.EventArgs e)
{
// Load control from file "MyUserControl.ascx"
Control myUserControl =(Control)Page.LoadControl("MyUserControl.ascx");
// Place web user control to place holder control
phModule.Controls.Add(myUserControl);
}
}
Finally, you can start an example and enjoy in dynamically loaded web user control, like in image bellow:
You can, depending of your needs, load different modules and easy provide different functionality in your ASP.NET web application.