What C# types can be accessed from ASP .net?

230 views Asked by At

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?

3

There are 3 answers

3
Darin Dimitrov On BEST ANSWER

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.

1
Emyr On

I did this yesterday:

<%@ Import Namespace="System.Linq" %>
0
Falanwe On

If you want to use namespaces that are not included by default, you have to import them à the start of your file. For exemple, for Dictionary, which is defined in the System.Collections.Generic namespace, you have to write:

<%@ Import Namespace="System.Collections.Generic" %>