Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass C# Array To Javascript

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
] 
like image 730
TheChampp Avatar asked Feb 17 '23 11:02

TheChampp


1 Answers

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.

like image 195
Matthew Avatar answered Feb 28 '23 12:02

Matthew