I have an issue currently that I can’t resolve. I have a user control called “Dashboard” which then has the following markup, containing several subcontrols.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Dashboard.ascx.cs" Inherits="BlueSEQ.Controls.Dashboard.Dashboard" %>
<%@ Register src="Administrator.ascx" tagname="Administrator" tagprefix="uc1" %>
<%@ Register src="Provider.ascx" tagname="Provider" tagprefix="uc2" %>
<%@ Register src="User.ascx" tagname="User" tagprefix="uc3" %>
<% if (isAdministrator)
{ %>
<uc1:Administrator ID="Administrator1" runat="server" />
<% }
else if (isProvider)
{ %>
<uc2:Provider ID="Provider1" runat="server" />
<% }
else
{ %>
<uc3:User ID="User1" runat="server" />
<% } %>
As you can see, I want it to display some controls or other controls depending on some conditions. However, all of these controls’ “Load” event get triggered, even if they are not used.
How can I prevent this?
If you can help it, try to avoid having conditional logic in your markup. It could make the views somewhat more difficult to understand for designers (if you’re working with designers) and more difficult to find and refactor this code in the future.
You should also take a look at ASP.NET MVC: Avoiding Tag Soup. Although it’s ASP.NET MVC, it’s still a good example of how adding logic to your views can quickly make them very difficult and unpleasant to maintain (initial example).
You could use the technique described here: How to: Add Controls to an ASP.NET Web Page Programmatically.
Your markup would look something like this.
and your codebehind would have something along the lines of