36

Having just started with MVC 2 I notice that in their starter template they use

<%: Html.ActionLink("Home", "Index", "Home")%>

and I was sure that in MVC 1 it was

<%= Html.ActionLink("Home", "Index", "Home")%>

Are they the same thing? If so, why the change from equal sign to colon.

Ralph Shillington
  • 20,718
  • 23
  • 91
  • 154

3 Answers3

43

the colon syntax means you'll be html encoded automatically: http://haacked.com/archive/2009/09/25/html-encoding-code-nuggets.aspx

They couldn't just html encode all the existing <%= blocks, because things that are already properly encoded (which is hopefully most of the projects out there) would look strange.

Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
12

<%= is used for writing to the output buffer.

<%: is used for writing to the output buffer, after HTML Encoding the content... Unless the IHtmlString Interface has been implemented on the returned object.

Scott Guthrie has an excellent post on this topic: http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx

If the output has already been escaped, double encoding can be prevented by implementing the IHtmlString Interface on the returned object. http://msdn.microsoft.com/en-us/library/system.web.ihtmlstring.aspx

gahooa
  • 131,293
  • 12
  • 98
  • 101
5

ASP .NET 4 introduced the <%: syntax which encoded the output before rendering it to the screen. ASP MVC already was encoding this but to be more explicit they began using the syntax as well to make it clear that whenever you see the <%: you can be sure the output will be properly encoded.

Matthew Manela
  • 16,572
  • 3
  • 64
  • 66