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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Method 2
<%= %> 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
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0