Reputation: 3030
I tried to find what the difference is between these two with Google, but I could not find an exact definition, and I could not exactly search for symbols either.
Right now I know that you can put a piece of code between <%# %> and you have to call Page.DataBind() method to apply it, I think this is how <%# %> works. But what does <%= %> mean? When should I use it?
Upvotes: 7
Views: 319
Reputation: 1
The Basic differences are:
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 and are used to reference properties or fields.
For example:
<%= Response.Write() %>
<ItemTemplate>
<%# DataBinder.Eval("Title") %>
</ItemTemplate>
You can have a more detailed explanation on msdn here: What's the difference between <%= %> and <%# %>
Hope this helps.
Upvotes: 10
Reputation: 111860
<%= %>
is used to reference properties/fields. It's like having a Response.Write
"inlined" in the page at that position.
<%# %>
is used for data binding with Eval/Bind. Taken from MSDN
The Eval method evaluates late-bound data expressions in the templates of data-bound controls such as the GridView, DetailsView, and FormView controls. At run time, the Eval method calls the Eval method of the DataBinder object,
ASP.NET 4.0 introduces <%: something %>
that is like <%= %>
but escapes content (so it converts <
to <
and so on)
So in the end you can use the <%# %> only in some controls (those that inherit from BaseDataBoundControl
)
There is an article here http://msdn.microsoft.com/en-us/library/aa479321.aspx that explains how the data binding is done in .NET
I'll add a link with a list of all the special inline tags of Asp.net: http://naspinski.net/post/inline-aspnet-tags-sorting-them-all-out-(3c25242c-3c253d2c-3c252c-3c252c-etc).aspx (it doesn't contain <%: %>
)
Upvotes: 4
Reputation: 460118
<%= ... %>
Used for small chunks of information, usually from objects and single pieces of information like a single string or int variable:
The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>
<%# .. %>
Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:
<asp:Repeater ID="rptMeetings" DataSourceID="meetings" runat="server">
<ItemTemplate>
<%# Eval("MeetingName") %>
</ItemTemplate>
</asp:Repeater>
MSDN: Data-Binding Expressions Overview
Internet resource: Inline asp.net tags... sorting them all out
Upvotes: 1