简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM