27

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?

John Sheehan
  • 75,663
  • 30
  • 157
  • 192
y0mbo
  • 4,552
  • 6
  • 39
  • 45

3 Answers3

44

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
Brian
  • 24,898
  • 16
  • 78
  • 165
Keith
  • 142,371
  • 70
  • 289
  • 413
  • 4
  • 1
    Quite a nice explanation here: http://michielvoo.net/blog/expressions-vs-statements-part-2-asp-net-code-block-types/ – Keith Jun 08 '09 at 13:26
  • 2
    Where does the phrase *bee-stings* come from? – user692942 Mar 15 '16 at 19:51
  • 3
    @Lankymart in the default Visual Studio colour schemes these were highlighted in black and yellow, so `%>` looked a little like a bee sting. – Keith Mar 15 '16 at 19:55
  • 1
    Thanks, I was just intrigued where the phrase came from in relation to ASP code blocks, I've never heard before. – user692942 Mar 15 '16 at 19:57
  • Looks like link you posted died back in 2013, but can still be accessed here [Expressions vs. Statements, part 2: ASP.NET Code Block Types via Archive.org](http://web.archive.org/web/20130203221323/http://michielvoo.net/blog/expressions-vs-statements-part-2-asp-net-code-block-types/) – user692942 Mar 15 '16 at 20:03
24

<%= %> 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
  • 75,663
  • 30
  • 157
  • 192
  • see Gui Starbuck answer https://stackoverflow.com/questions/115159/when-should-i-use-and-in-asp-net-controls/115205#115205 for the differences between – Max Feb 05 '19 at 07:52
9

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
  • 21,125
  • 6
  • 52
  • 63