Access inline variable at front end using javascript

I publicly declared Dictonary in the code behind:

  Public dics As New Dictionary(Of String, String()) From { _ {"picture", New String() {".jpeg", ".jpg", ".png", ".bmp", ".gif", ".tif"}}, _ {"document", New String() {".doc", ".docx", ".txt", ".htm", ".html", ".xml", ".xaml", ".css"}}, _ {"excel", New String() {".xls", ".xlsx", ".xlt", ".xla"}}, _ {"pdf", New String() {".pdf"}}, _ {"zip", New String() {".7z", ".APK", ".BAT", ".rar", ".dll", ".jar", ".zip"}}, _ {"ppt", New String() {".ppt", ".pos", ".pps"}}} 

Edit:

if i like it

 function myFunction() { var dic = "<%= dics %>"; var array_keys = new Array(); var array_values = new Array(); for (var key in dic) { alert(key); } } 

will display warnings as this

How can I access this Dictonary in javascript to do some operations

+5
source share
2 answers

Now it looks like you need to serialize the dictionary in a javascript object and then paste it into your JavaScript. You can use any library for serialization. For instance. Newtosoft.Json . Like this:

 function myFunction() { var dic = <%= Newtonsoft.Json.JsonConvert.SerializeObject(dics) %>; var array_keys = new Array(); var array_values = new Array(); for (var key in dic) { alert(key); } } 

Please note that I removed the quotation marks.

But I suggest you get rid of this approach, and not mix JavaScript and ASP.Net code. Therefore, in my vision, you should download this dictionary via AJAX or, if this is not possible, put ASP.Net in a different location. For instance:.

View:

 <input type="hidden" id="dictionaryInput" value="<%=Newtonsoft.Json.JsonConvert.SerializeObject(dics)%> /> 

JavaScript:

 function myFunction() { var dicInput = document.getElementById('dictionaryInput'); var dic = JSON.parse(dicInput.value); var array_keys = new Array(); var array_values = new Array(); for (var key in dic) { alert(key); } } 

Hope this helps.

+2
source

You can create a property (e.g. DictionaryConv) in your code behind, and in the page load, this is the value of the property.

 Dim jsz As New System.Web.Script.Serialization.JavaScriptSerializer DictionaryConv = jsz.Serialize(dics) 

In javascript you use this function.

 function myFunction() { var dic = <%= DictionaryConv%>; var array_keys = new Array(); var array_values = new Array(); for (var key in dic) { alert(key); } } 
0
source

Source: https://habr.com/ru/post/1202650/


All Articles