I know that <%: does the html.encode thing, but there are lots of situations when I'm sure that I don't need to encode, so why should I waste time on encoding stuff that I'm 100% sure it doesn't require to be encoded like for example <%:Url.Action("Index") %>
or <%: Model.Id %>
(is of type int)?
The :
code nugget is part of the ASP.NET 4.0 web compiler and doesn't just call Html.Encode()
. It works out whether or not the string is already encoded first (if the expression returns an IHtmlString
then it probably won't get encoded).
This means it is safe to use it when inserting actual data or when inserting HTML from some type of helper method (if you write your own helper methods, they should always return IHtmlString
as of MVC 2).
With regards to whether or not you always use it, of course you don't. But I'd rather not think about it too much and will be happier knowing I've gone some way towards fending off XSS attacks with little effort; therefore, I nearly always use it.
It also encourages you to make sure you return a MvcHtmlString
from your HTML helper methods rather than a string
.
One example where you would not want to use <%: is for strings that come from your resource file that include HTML escape characters. I don't think you can make a blanket statement that you should always use <%:.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With