views:

46

answers:

1

The following is taken from page 56 of Professional ASP.NET MVC 1.0.

When we look at the Details.aspx template more closely, we’ll find that it contains static HTML as well as embedded rendering code. <% %> code nuggets execute code when the view template renders, and <%= %> code nuggets execute the code contained within them and then render the result to the output stream of the template.

The statement intrinsically makes sense, but I was unable to clearly articulate to a team member exactly what it meant. A more detailed explanation of what exactly is occurring would be useful.

An example of usage from later in the chapter:

<% foreach (var dinner in Model) { %>
    <li>
        <%= Html.Encode(dinner.Title) %>
        on
        <%= Html.Encode(dinner.EventDate.ToShortDateString())%>
        @
       <%= Html.Encode(dinner.EventDate.ToShortTimeString())%>
    </li>
<% } %>
+1  A: 

Basically <% %> just executes code and doesn´t output anything while <%= %> generates some form of output to the browser.

For example take <% foreach (var dinner in Model) { %>. This line just means we loop over a collection if items and there must be some matching end loop <% } %> for the page to be syntactically correct. Nothing is send to the browser because of this loop by itself.

Sending something to the browser is done using <%= Html.Encode(dinner.Title) %>. This takes the contents of the dinners Title, HtmlEncodes whatever is in there and writes it to the response stream.

Maurice