views:

61

answers:

2

I want to be able to send data to Javascript in a div like this:

<div class="dontDisplay><%= myData %></div>

However, the challenge is that the HTML will get messed up. There seems to be a plethora of encoding and decoding schemes out there, but I can't find a javascript/C# pair that are guaranteed to be compatible for all possible inputs (including Unicode.)

Does anyone know of a pair that are known to be perfectly compatible?

Thanks

+1  A: 

You most probably want to use json. You can embed a string in your page that creates a local variable on your page using json inside a script-tag:

<script> var myJsonVariabe = { propertyNane: "value" }; </script>

You can serialize a .net object to json using the DataContractJsonSerializer.

Rune Grimstad
+1  A: 

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.

bobince
Mike Jones
bobince