简体   繁体   中英

What's the difference between <%= %> and <%# %>?

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?

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.

  • <%= %> 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 &lt; 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 <%: %> )

<%= ... %>

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

MSDN: Displaying from ASP.NET

<%# .. %>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM