R – ASP.NET custom control rendering before <%= %> code executes to populate property

asp.netcustom-server-controls

I have a custom control that exposes a property. When I set it using a fixed value, everything works correctly. But if I try to set its value using the <%= %> tags, it goes a little whacky:

<cc:CustomControl ID="CustomControl" runat="server" Property1='<%= MyProperty %>' />
<%= MyProperty %>

When this gets rendered, the <%= MyProperty %> tag underneat the custom control is rendered as I expect (with the value of MyProperty). However, when I step into the Render function of the CustomControl, the value for Property1 is literally the string "<%= MyProperty %>" instead of the actual underlying value of MyProperty.

Best Answer

You control is initialized from the markup during OnInit. So if that syntax worked, it wouldn't have the effect you wanted anyway, since MyProperty would be evaluated during OnInit and not at render time (like it is with the second usage).

You want to use the data binding syntax instead:

<cc:CustomControl ID="CustomControl" runat="server" Property1='<%# MyProperty %>' />

Just make sure to call DataBind() on the container (Page, UserControl, etc).

Alternatively, you can set the property in your code behind:

CustomControl.Property1 = MyProperty;
Related Topic