15

What is the difference between <% %> and <%= %> in ASP.NET MVC? And when to use which?

Graviton
  • 81,782
  • 146
  • 424
  • 602

4 Answers4

37

See also this question. MVC hasn't changed how these bee-stings work, just how often they're used.

Basically:

  • <% - execute code
  • <%@ - 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
Community
  • 1
  • 1
Keith
  • 150,284
  • 78
  • 298
  • 434
10

<%= %> writes to the output stream (usually html) while <% %> is for executing arbitrary script code.

Tahir Akhtar
  • 11,385
  • 7
  • 42
  • 69
8

Say you have a method on your page, called "SayHello":

protected string SayHello()
{
    return "Hello!";
}

And on your page, you have these statements:

first: <%= SayHello() %>
second: <% SayHello() %>

Your output will be:

first: Hello!
second: 

when you use <%= %>, what you put in there is inserted into the html at that position. If you use <% %>, you're just inserting some code into your page.

Erik van Brakel
  • 23,220
  • 2
  • 52
  • 66
3

<%= echos the statement out.

<% just runs it.

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241