MVC2 how is <%: tag different to <%=
what开发者_运维技巧 is the difference between <%: and <%= ?
The difference is that <%: automatically HTML encodes the string whereas <%= does not.
Back before MVC2 came out in order to HTML encode a string you had to use the Html.Encode() method inside the view.
<%= Html.Encode(Model.MyString) %>
However with MVC2 they added the <%: tag, which outputs the same thing but handles the HTML encoding for you.
<%: Model.MyString %>
As a rule of thumb you should always output your strings using the <%: tag, unless you have a good reason not to.
Checkout Scott Gu's blog for more information on the subject.
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...
Essentially, the <%:
tag encodes any strings that haven't already been encoded. So:
<%: Model.Title %>
... is the same as:
<%= Server.HtmlEncode(Model.Title ) %>
But if you accidentally use the tag where it wasn't necessary:
<%: Html.TextBoxFor(Model => Model.Title) %>
... it will be the same as if you hadn't:
<%= Html.TextBoxFor(Model => Model.Title) %>
See 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 for a full explanation.
精彩评论