Home > DeveloperSection > Forums > How to access a backend variable in front end using javascript
Chintoo Semi

Total Post:135

Points:947
Posted on    February-05-2015 10:26 PM

 ASP.Net VB.Net  JQuery  JavaScript 
Ratings:


 1 Reply(s)
 725  View(s)
Rate this:

I had Public declared Dictonary in code behind as :

 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 do like this

function myFunction() {

       var dic = "<%= dics %>";

       var array_keys = new Array();

       var array_values = new Array();

       for (var key in dic) {

           alert(key);

        }

     }

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



john rob

Total Post:108

Points:756
Posted on    February-05-2015 10:53 PM

For now it looks like you need to serialize dictionary into javascript object and then paste it in your JavaScript. You could use any library for serialization. E.g. 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);

    }

 }

Note that I removed quotes.

But I suggest you to get rid of this approach and not mix JavaScript and ASP.Net code. So in my vision you should load this dictionary via AJAX or if it's not possible place ASP.Net in some other place. E.g.:

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 it will help.


Don't want to miss updates? Please click the below button!

Follow MindStick