5

As far as I can tell, both of these tag types do the same thing. Which is preferred to use?

5 Answers 5

8

It calls an HtmlEncode on the value

See ScottGu's blog for more info.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Sometimes I come across a question I had but never got around to asking...
4

They are not the same:

<%=%> is the same as `Response.Write`
<%:%> adds `Server.HtmlEncode` to `Response.Write`

Hence, <%:%> is preferred (added since .NET 4.0), as it adds the security measure of encoding the output before outputting the string.

If you are using .NET 3.5 or before, best practice is to use <%=Server.HtmlEncode(val)%>.

1 Comment

@Praveen Prasad - I believe they are supposed to be doing the same job, but in practice a bit different (not enough to cause problems, but one is stricter than the other, if memory serves).
2

<%: %> would be preferred as it automatically HTML Encodes the value, however it only works in .NET 4.

Comments

2
<%: someString %>

is like

<%= HttpUtility.HtmlEncode(someString) %>

Comments

2

You use " <%:" when you need to sanitize the string (i.e from something that was inputed by an user and can be potentially malicious)

Basically <&= just writes as string as it is to the HTML and <%: is the same as writing <%= Html.Encode("something") %>

1 Comment

<%: %> is generally better. In the Razor view engine, Microsoft made that it so that the @ is the equivalent to <%: %>. And you need to use @Html.Raw(value) to get the equivalent <%= %> behavior.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.