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
Solution 1:
You need to serialize the array to JSON. One way to do it is with JavaScriptSerializer...
using System.Web.Script.Serialization;
// ...protectedstringnumArrayJson()
{
int [] hi = {1,2};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(hi);
return json;
}
Now this should work...
vararray = <%=numArrayJson()%>;
The actual script outputted to the page should look like this...
vararray = [1,2]; // a javascript array with 2 elements
window.alert(array[0]); // 1
window.alert(array[1]); // 2
Solution 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.
Post a Comment for "How Do I Send My Values From C# To Javascript With Asp.net"