A_Var
A_Var

Reputation: 1036

view template code tags - asp.net mvc - regd

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

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

Upvotes: 5

Views: 1037

Answers (2)

Alex Reitbort
Alex Reitbort

Reputation: 13696

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.

Upvotes: 7

Related Questions