Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I always use <%: instead of <%=

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)?

like image 672
Omu Avatar asked Jul 20 '10 09:07

Omu


2 Answers

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.

like image 62
David Neale Avatar answered Oct 16 '22 22:10

David Neale


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 <%:.

like image 39
Jedidja Avatar answered Oct 17 '22 00:10

Jedidja