How to send my values ​​from C # to javascript using asp.net

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

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

I am trying to get these values ​​in my javascript, so I am 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 the string ("System.Int32 []"). The first warning prints "S", and the second prints "y". How can I print my numbers. Should I return a string from my C # code?

0
source share
2 answers

You need to serialize the array in JSON. One way to do this 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()%>;

script, , :

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

# int, javascript . JSON, JavaScript. .ToString() , ( ), javascript.

0

All Articles