TheChampp
TheChampp

Reputation: 1437

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
] 

Upvotes: 4

Views: 10744

Answers (2)

Matthew
Matthew

Reputation: 25793

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.

Upvotes: 8

hnafar
hnafar

Reputation: 611

your c# code will return a string, you have to first parse the string using JSON.parse, and then iterate through it:

var a = JSON.parse('<%= this.javaSerial.Serialize(this.names) %>');
for (var i = 0; i < a.length; i++) {
    console.log(a[i]);
}

or maybe as @Matthew said, don't put quotes around it, so you won't have to parse it.

Upvotes: 0

Related Questions