views:

610

answers:

4

I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate.

For example:

<%= Grid.ClientID %>

or

<%# Eval("FullName")%>

Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding?

+18  A: 

<%= %> 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

John Sheehan
+3  A: 

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.
Guy Starbuck
"<%= expressions cannot." Because <%= %> is a shortcut for Response.Write which happens _*after*_ the page is rendered and the response is being streamed back to the browse.
AMissico
+20  A: 

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
Keith
Very concise, thanks.
KevDog
<%$ is not just for resource access, but for ExpressionBuilders - of which ConnectionStrings, AppSettings, and Resource are included in ASP.NET. It's also trivial to write your own. http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.aspx
Mark Brackett
Quite a nice explanation here: http://michielvoo.net/blog/expressions-vs-statements-part-2-asp-net-code-block-types/
Keith