How to use ASP.NET <%= tags in server control attributes?

Viewed 84006

This works:

<span value="<%= this.Text %>" />

This doesn't work:

<asp:Label Text="<%= this.Text %>" runat="server" />

Why is that?

How can I make the second case work properly, i.e., set the label's text to the value of the "Text" variable?

7 Answers

Just pitching this little nugget in for those who want a good technical breakdown of the issue -- https://blogs.msdn.microsoft.com/dancre/2007/02/13/the-difference-between-and-in-asp-net/

I think the crux is in pretty decent agreement with the other answers:

  • The <%= expressions are evaluated at render time
  • The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.
  • <%# expressions can be used as properties in server-side controls. <%= expressions cannot.
Related