Tuesday, April 5, 2011

What does mean ":" in <%: and what is the difference to <%= ?

Hi

In ASP.NET MVC 2 <%: tag was introduced to replace <%= for Html helpers. But what does it mean and what is the difference to the previous one? When shall I use <%= and when <%:?

Thank you

From stackoverflow
  • IIRC, <%: automatically provides HTML encoding so you don't need to do it yourself.

    From Scott Guthrie's blog post:

    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.

    Read the blog post for a lot more detail.

  • <%= Injects the value directly whereas <%: automatically escapes all of the scary special characters for you.

    In other words,

    <%: myString %>

    is the same as

    <%= Server.HtmlEncode(myString) %>

  • In ASP.NET 4 the <%: xyz %> syntax will do the same thing as <%= Server.HtmlEncode(xyz) %> did in previous versions. It is simply a shortcut because it is used so often.

    As Richard says below, it can also determine if a string does not need to be encoded based on whether or not it implements the IHtmlString interface.

    Richard : It also provides for avoiding the HTML Encode if the type of the expression implements the `IHtmlString` interface -- so types that do their own encoding don't need special treatment.

0 comments:

Post a Comment