What are the difference between <%: and <%= in ASP .NET MVC 3

I'm just wondering, the only difference I know is that the <%= symbols generates any possible html tags that's included with the string your planning to display, while <%: just display what the string exactly look like. If anyone can help me with this, I will greatly appreciate it.

Upvotes: 0

Views: 125

Answers (4)

Jakub Konecki
Jakub Konecki

Reputation: 46008

From Scott Gu blog:

With ASP.NET 4 we are introducing a new code expression syntax (<%: %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so. This eliminates the need to explicitly HTML encode content like we did in the example above. Instead, you can just write the more concise code below to accomplish the exact same thing:

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

Upvotes: 0

Erik Philips
Erik Philips

Reputation: 54618

Pretty good explanation from Scott Gu - New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)

Excerpt:

ASP.NET applications (especially those using ASP.NET MVC) often rely on using <%= %> code-nugget expressions to render output. Developers today often use the Server.HtmlEncode() or HttpUtility.Encode() helper methods within these expressions to HTML encode the output before it is rendered. This can be done using code like below:

<div>
  <%= Server.HtmlEncode(Model.Content) %>
</div>

While this works fine, there are two downsides of it:

It is a little verbose Developers often forget to call the Server.HtmlEncode method – and there is no easy way to verify its usage across an app

New <%: %> Code Nugget Syntax

With ASP.NET 4 we are introducing a new code expression syntax (<%: %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so. This eliminates the need to explicitly HTML encode content like we did in the example above. Instead, you can just write the more concise code below to accomplish the exact same thing:

<div>
  <%: Model.Content %>
</div>

Upvotes: 2

Jacek Glen
Jacek Glen

Reputation: 1546

The two inline code tags are essentialy the same, the only difference being that <%: %> will automatically use encoding. So this:

<%: myText %>

is equivalent to this:

<%= Html.Encode(myText) %>

The former is recommended.

Upvotes: 2

Ravi Gadag
Ravi Gadag

Reputation: 15861

<%: is HtmlEncoded. Code Nuggets for asp.net

With ASP.NET 4 we are introducing a new code expression syntax (<%: %>) that renders output like <%= %> blocks do – but which also automatically HTML encodes it before doing so.

Upvotes: 0

Related Questions