When should I use # and = in ASP.NET controls? When should I use # and = in ASP.NET controls? asp.net asp.net

When should I use # and = in ASP.NET controls?


There are a couple of different 'bee-stings':

  • <%@ - page directive
  • <%$ - resource access
  • <%= - explicit output to page
  • <%# - data binding
  • <%-- - server side comment block

Also new in ASP.Net 4:

  • <%: - writes out to the page, but with HTML encoded

Also new in ASP.Net 4.5:

  • <%#: - HTML encoded data binding


<%= %> is the equivalent of doing Response.Write("") wherever you place it.

<%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind)

Databinding Expressions Overview


Here's a great blog post by Dan Crevier that walks through a test app he wrote to show the differences.

In essence:

  • 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.