简体   繁体   中英

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:

  • <% %> 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?

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. ie 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. ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM