You appear to be just putting some text into HTML text content, for which the correct approach is plain old HTML-encoding:
<div class="dontDisplay"><%= Server.HTMLEncode(myData) %></div>
or in ASP.NET 4.0:
<div class="dontDisplay"><%: myData %></div>
If JavaScript needs to extract this, you can use DOM methods:
<div id="foo"><%= Server.HTMLEncode(myData) %></div>
<script type="text/javascript">
var myData= document.getElementById('foo').firstChild.data;
</script>
although this assumes that there's exactly one text node in there, and will break if myData
is an empty string. You can work around this by having a getTextContent
method that checks all the childNodes
for being text nodes and adds their data
together, or use textContent
with fallback to innerText
for IE, or use a library to do it (eg. text()
in jQuery).
alternatively you can put the data in an attribute:
<div id="foo" title="<%= Server.HTMLEncode(myData) %>">...</div>
<script type="text/javascript">
var myData= document.getElementById('foo').title;
</script>
if there is a suitable attribute available (title
might not be appropriate), or a comment, or directly into a JavaScript variable using JSON as suggested by Rune.