views:

102

answers:

6

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

A: 

One of the advantages of encoding to HTML is that it makes the pages W3C Valid according to corresponding datatype. So why validate the document in the first place?

For the answer to that please check, please check: http://validator.w3.org/docs/why.html

Briefly validating HTML saves a lot of time later in the development cycle and its a good practice.

GeekTantra
You mean as in 𞃳 values? I think he's actually asking if he needs to use `<%:` for `<%: number.ToString() %>` where he can be sure he'll only ever generate strings without special characters and cannot contain injected tags because they're completely under his control.
Rup
A: 

Its easier, if you use only one type, and makes the code more clean. also, you never know, who will change the code, and makes out of a simple "100 %" statement, a not so 100% statement :-)

Normally, in a web environment, the performance on such things are not an issue.

i would suggest to only use "<%:" as a team development guideline. just to be on the safe side.

cRichter
+4  A: 

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

Jedidja
+3  A: 

Personally I use it only for stuff that I know that needs to be encoded. No need to use it for integer types <%: Model.Id %> but that's just a personal preference.

Darin Dimitrov
+7  A: 

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.

David Neale
+1  A: 

<%: model %> is equivalent of <%= Html.Encode(model)%>

using <%: saves keystrokes and improves your productivity,

but sometimes you will have a need to do <%= (not to encode whatever you are displaying on your page)

Nikola Markezic