0

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?

3
  • If you're using .Net, are you using WebForms or is this a service call through WCF or an API controller? Commented Apr 24, 2014 at 16:39
  • sorry, I'm using ASP.Net Commented Apr 24, 2014 at 16:41
  • Are you using WebForms or MVC? Either way, you can't call server-side functions directly from JavaScript unless you use AJAX or do a postback. Commented Apr 24, 2014 at 16:56

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

this sorta works for me. When I did that, my js is getting a string that looks like this: "[1,2]". So to index my values I have to use array[1] and array[3] in order to skip the comma and brackets. Is there a cleaner way?
Make sure you don't have quotes around <%=numArrayJson()%>.
yep, it was the quotes that was causing this. thanks
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.