Let's say I have a class called ApplicationSettingsManager, and I have a String that needs referencing from Javascript on my ASP .net page, I have done the following:
<%=ApplicationSettingsManager.IdNumber %>
And it works fine. But what if I need to reference a Dictionary<String,String>
? Or any other slightly more complex type? Is it possible? Do I need to use serialization somehow?
Do I need to use serialization somehow?
Yes, it is recommended to use JSON serialization when passing complex types to javascript. For example you could use the JavaScriptSerializer class:
<script type="text/javascript">
var value = <%= new JavaScriptSerializer().Serialize(AnyComplexObjectYouLike) %>;
</script>
Example with a Dictionary<string, string>
:
<script type="text/javascript">
var value = <%= new JavaScriptSerializer().Serialize(new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }) %>;
alert(value.key1);
</script>
which will render as:
<script type="text/javascript">
var value = {"key1":"value1","key2":"value2"};
alert(value.key1);
</script>
in the final markup.