views:

39

answers:

2

What is the difference between <% %> and <%: %> in context of asp.net MVC view engine. In the MVC2 book it's given as follows:

  • <% %> code nuggets execute code when the View template renders.
  • <%: %> code nuggets execute the code contained within them and then render the result to the output stream of the template.

When to use the first and when to use the second?

+1  A: 

The book is almost correct:

<% %> code nuggets execute code when the View template renders. So if you put a call to function <div><% MyFunc() %></div> the you function will be executed at the rendering time after opening tag if div was rendered but before closing tag was rendered. The function may do anything you want, check some conditions and fail with exception, set some variables, use HttpContext.CurrentContext.Response.Write (or just Response.Write in webforms) to write to response stream.

<%: %> code nuggets execute the code contained within them and then render the result html encoded to the output stream of the template. i.e it is the same as <% HttpServerUtility.HtmlEncode(HttpContext.CurrentContext.Response.Write(MyFunc()))%>

<%= %> code nuggets execute the code contained within them and then render the result without html encoding to the output stream of the template. i.e it is the same as <% HttpContext.CurrentContext.Response.Write(MyFunc())%>

---MyFunc() in last two cases should return a string. It can also be a reference to some property of ViewModel or any other code nugget that evaluates to string.

Alex Reitbort