DannyD
DannyD

Reputation: 2901

How do I send my values from c# to javascript with asp.net

I have a simple c# function that returns an array like this:

protected int[] numArray()
{
    int [] hi = {1,2};
    return hi;
}

I'm trying to get these values into my javascript so I'm trying to do this in asp.net:

var array = '<%=numArray()%>';
window.alert(array[0]);
window.alert(array[1]);

However, instead of passing the array back, it seems to pass a string ("System.Int32[]"). The first alert prints an 'S' and the second prints a 'y'. How can I print my numbers instead. Will I have to return a string from my c# code?

Upvotes: 0

Views: 620

Answers (2)

Anthony Chu
Anthony Chu

Reputation: 37540

You need to serialize the array to JSON. One way to do it is with JavaScriptSerializer...

using System.Web.Script.Serialization;
// ...
protected string numArrayJson()
{
    int [] hi = {1,2};
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(hi);
    return json;
}

Now this should work...

var array = <%=numArrayJson()%>;

The actual script outputted to the page should look like this...

var array = [1,2];      // a javascript array with 2 elements
window.alert(array[0]); // 1
window.alert(array[1]); // 2

Upvotes: 3

Ace Hyzer
Ace Hyzer

Reputation: 355

You are passing back a C# int array, which javascript can't read. Your best bet would be to convert it to JSON and then send it back and parse that with the JavaScript. Another option would be to simply to .ToString() on the array before you return it (or when you bind it) and then parse that with the javascript.

Upvotes: 0

Related Questions