Search code examples
c#asp.netcustom-controlsweb-controls

How to set custom object property on ASP.NET WebControl through markup


I am struggling how to set a custom property which is suppose to point to an instance of my custom class on an ASP.NET webcontrol.

Sample web control:

public class CustomControl : System.Web.UI.WebControls.Panel
{
  public IFactory Factory { get; set; }
}

Code behind:

public partial class Main : System.Web.UI.Page
{        
  public IFactory GetFactory { 
    get { return new CustomFactory(); } 
  }
}

public class CustomFactory : IFactory {}

The custom factory get initialized on the code behind. In my markup (not in code behind), I need to set the Factory property on my CustomControl to the instance in my code behind. Any variation of inline code that I tried did not work:

<asp:CustomControl ID="MyCustomControl" Factory="<%GetFactory%>" runat="server" />
<asp:CustomControl ID="MyCustomControl" Factory="<%=GetFactory%>" runat="server" />

Can anyone assist how to do this?


Solution

  • You just can't assign it on the control tag markup, the tag markup is rendered as html and has no logic to do it that way, html won't interpret te result of GetFactory. What you can do is to set if on your markup, not it the control tag property, but inside code brackets just like this:

    <%MyCustomControl.Factory = this.GetFactory;%>