What is the difference between <%#%> and <%=%>?
Answer Posted / vinodh reddy
I was a little confused about the difference between <%=
expression %> and <%# expression %> in ASP.NET. It seems
like both work in a lot of cases, but in other cases, only
the # (data binding) version works. So, I decided to dig
into it a little bit. To try it out I built this simple
page:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE
html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd"><html
xmlns="http://www.w3.org/1999/xhtml" ><head
runat="server"> <title>Untitled
Page</title></head><body> <form id="form1"
runat="server"> <div> <p>Equals: <%=
this.TestValue %></p> <p>Pound: <%# this.TestValue %
></p> <p>Equals label: <asp:Label runat="server"
ID="_equals" Text="<%= this.TestValue %>" /></p>
<p>Pound label: <asp:Label runat="server" ID="_pound"
Text="<%# this.TestValue %>" /></p> </div>
</form></body></html>
And the code behind is:
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{ _testValue = "2"; } protected void
Page_PreRenderComplete(object sender, EventArgs e)
{ // DataBind(); _testValue = "3"; }
public string TestValue { get { return
_testValue; } } private string _testValue = "1";}
Here's what the result is when the DataBind() line is
commented out:
Equals: 3
Pound:
Equals label:
Pound label:
And, when it's not commented out:
Equals: 3
Pound: 2
Equals label:
Pound label: 2
At first glance it looks like the Equals label case did
nothing. But, if you view source, you see:
<p>Equals label: <span id="_equals"><%= this.TestValue %
></span></p>
The literal expression made it down to the browser and it's
just invalid HTML. What you can see as a result is:
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.
Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers
What is the difference between visual basic and asp.net?
What is latest version of asp.net mvc? : Asp.Net MVC
Where would you use an ihttpmodule, and what are the limitations if any?
What threading model used in asp and asp.net?
What are the Types of objects in ASP
How to create multi language website in asp.net mvc? : Asp.Net MVC
What are the asp.net server side objects?
What is the procedure to create the environment for asp.net? : asp.net mvc
What is a master page and what does it do?
What do you mean by caching in asp.net?
Which two new properties are added in asp.net 4.0 page class?
What is different authentication mechanisms used in ASP.NET?
What is %20 in a url?
What is a swagger in web api?
Can you explain why it is useful to use mvc instead of webforms? : asp.net mvc