What is the difference in <%: variable%> and <%= variable%> in ASP.NET MVC?

With many folks adopting ASP.NET MVC as well as Visual Studio 2010, there is a fairly confusing change if you are one of those people who doesn’t engage in the alpha and beta phases of new product releases from Microsoft or any other vendor, for that matter.

The issue of <%: vs. <%= has had a great deal of discussion around it in the years leading up to the Visual Studio 2010 release.  This new expression syntax, or code nugget, is a new feature of ASP.NET 4.  It applies equally to ASP.NET Web Forms and ASP.NET MVC applications that are using the Web Forms view engine (ASPX).

In short, <%: ViewData["Message"] %> does the same thing as <%= Html.Encode(ViewData["Message"]) %>.

When creating a new ASP.NET MVC web application in Visual Studio 2010, you will see that the default Home/Index.aspx view is as follows.

image

However, if you create an ASP.NET MVC 2 web application in Visual Studio 2008, you see that ViewData[“Message”] is printed using the syntax that heralds back to the IDC/HTX technology of IIS 2.

image

I hope this tidbit helps in sorting through code samples online.  If you see <%: %>, you know that the code sample was produced for ASP.NET 4 or later.