What is the best way to pass C# array to javascript variable ?
I have sample code but this return character by character from C# array, I want to return in normal way like word by word in javascript array;
C# code behind:
public string[] names = { "John", "Pesho", "Maria"};
public JavaScriptSerializer javaSerial = new JavaScriptSerializer();
javascript code:
<script>
var a = '<%= this.javaSerial.Serialize(this.names) %>';
for (var i = 0; i < a.length; i++) {
console.log(a[i]);
}
</script>
This script return all words from "names" array in single char array . I want to return in normal way like ["John"] ["Pesho"] ...
What is the best way to pass C# array to javascript ?
When I run this code I get the following in console of Chrome browser:
[ Profile.aspx:44
" Profile.aspx:44
v Profile.aspx:44
a Profile.aspx:44
l Profile.aspx:44
e Profile.aspx:44
r Profile.aspx:44
i Profile.aspx:44
" Profile.aspx:44
, Profile.aspx:44
" Profile.aspx:44
p Profile.aspx:44
e Profile.aspx:44
s Profile.aspx:44
h Profile.aspx:44
o Profile.aspx:44
" Profile.aspx:44
, Profile.aspx:44
" Profile.aspx:44
m Profile.aspx:44
a Profile.aspx:44
r Profile.aspx:44
i Profile.aspx:44
a Profile.aspx:44
" Profile.aspx:44
]
Replace
var a = '<%= this.javaSerial.Serialize(this.names) %>';
with
var a = <%= this.javaSerial.Serialize(this.names) %>;
You were putting the resulting JSON into a javascript string, which would result in your example output iterating through each character of the Serialize
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With