15

Possible Duplicates:
What is the difference between <% %> and <%=%>?
C# MVC: What is the difference between <%# and <%=

I'm so confused with this.

Please explain the difference between this if possible..

What is the significance of that "=" there?

Edit:Thanks for all your answers.Please understand that It was hard to get any results by searching for "<%=" on google and on the search bar in stackoverflow as well.

Community
  • 1
  • 1
Josh
  • 13,530
  • 29
  • 114
  • 159

4 Answers4

35

<% %> is a generic code block.

<%= expression %> is equivalent to <% Response.Write(expression); %>.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
8

It is confusing, and it takes a good deal of repetition to get comfortable with.

The <%= syntax is used for evaluating expressions whose returned values are intended to be included within HTML markup. For example:

<%= DateTime.Now.ToShortDateString() %>

This will include the current date in the HTML markup.

The <% is for inline statements, where you want to execute one or more commands at a specific point during the page rendering. I've used Html Helpers in the past by executing the helper method using <%. For example,

<% Html.TextBox("txtBox"); %>

Note that the statements used here have to be terminated with a semicolon in C# code.

EDIT: Removed erroneous details about Html helpers and void returns.

David Andres
  • 31,351
  • 7
  • 46
  • 36
  • Actually, almost all of the Html Helpers return a string rather than writing to the Response object - <%= Html.TextBox("txtBox") %>. This allows you to e.g. nest helper methods. – Iain Galloway Sep 08 '09 at 12:57
  • 3
    `<% Html.TextBox("txtBox"); %>` silently discards the return value and doesn't output anything. – Mehrdad Afshari Sep 08 '09 at 12:59
3

<%= %> tag prints the output of the code in it, <% %> just runs the code.

pompo
  • 237
  • 1
  • 9
3

This post lists all the varieties nicely: ASP.NET "special" tags.

I would normally post this as a comment but there are a number of other dupes. I recall someone referring to them as "bee stings" (not official terminology) and the keywords I used to search for them were asp.net bee stings.

That said, here are some other dupes:

Community
  • 1
  • 1
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174