views:

480

answers:

3

Can I get a 'when to use' for these and others?

<% %>
<%# EVAL() %>

Thanks

+12  A: 

Check out the Web Forms Syntax Reference on MSDN.

For basics,

  • <% %> is used for pure code blocks. I generally only use this for if statements

    <% if (IsLoggedIn) { %>
      <div class="authenticated">
    <% } else { %>
      <div class="unauthenticated">
    <% } %>

  • <%= Expression %> is used to add text into your markup; that is, it equates to <% Response.Write(Expression) %>

    <div class='<%= IsLoggedIn ? "authenticated" : "unauthenticated" %>'>

  • <%# Expression %> is very similar to the above, but it is evaluated in a DataBinding scenario. One thing that this means is that you can use these expressions to set values of runat="server" controls, which you can't do with the <%= %> syntax. Typically this is used inside of a template for a databound control, but you can also use it in your page, and then call Page.DataBind() (or Control.DataBind()) to cause that code to evaluate.

The others mentioned in the linked article are less common, though certainly have their uses, too.

bdukes
+2  A: 

You can also use

<%= Class.Method() %>

And it will print the result, just as you can do in Ruby on Rails.

Brian Warshaw
+2  A: 

Just want to add, there's also the resources expression

<%$ Resources:resource, welcome%>

and asp.net would look for localized version of "welcome" in satellite assemblies automatically.

chakrit