Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<%: %> brackets for HTML Encoding in ASP.NET 4.0

Accidentally I found this post about a new feature in ASP.NET 4.0: Expressions enclosed in these new brackets <%: Content %> should be rendered as HTML encoded.

I've tried this within a databound label in a FormView like so:

<asp:Label ID="MyLabel" runat="server" Text='<%: Eval("MyTextProperty") %>' />

But it doesn't work: The text property contains script tags (for testing), but the output is blank. Using the traditional way works:

<asp:Label ID="MyLabel" runat="server"
    Text='<%# HttpUtility.HtmlEncode(Eval("MyTextProperty")) %>' />

What am I doing wrong?

(On a sidenote: I am too stupid to find any information: Google refuses to search for that thing. The VS2010 Online help on MSDN offers a lot of hits, but nothing related to my search. Stackoverflow search too. And I don't know how these "things" (the brackets I mean) are officially called to have a better search term.)

Any info and additional links and resources are welcome!

Thanks in advance!

like image 241
Slauma Avatar asked May 24 '10 18:05

Slauma


2 Answers

You are confusing data binding expressions, which have the syntax <%#%> and are used with Eval (and Bind) with the response output tags (<%=%> and <%:%>) that cannot be used with Eval.

like image 51
Oded Avatar answered Sep 20 '22 14:09

Oded


Use the <%#: %> HTML encoding databinding syntax. (Notice the ':' after the '#'). For example:

Text='<%#: Eval("PropertyToEval") %>'
like image 33
yhayes Avatar answered Sep 19 '22 14:09

yhayes