Passing C # array in java script

I have an array in my page_load in C # that I want to get in a java script but don't know how to do it.

float [] energyArray = new float[count]; for (int i = 0; i < count; i++) { energyArray[i] = energyObj[i].FwdHr; } 

Now I want to access javascript instead of data-

 series: [{ name: 'Tokyo', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }] 
+4
source share
5 answers

A very simple way is to use the JavaScriptSerializer class to convert your C # object to JSON:

WITH#

 float [] energyArray = new float[count]; for (int i = 0; i < count; i++) { energyArray[i] = energyObj[i].FwdHr; } 

Javascript:

 var dataArray = <%=new JavaScriptSerializer().Serialize(energyArray);%>; var series = [{ name: 'Tokyo', data: dataArray }]; 
+7
source

Changing your problem a bit ...

Instead of manipulating an existing script, consider building the whole block of a javascript string, and then use Page.RegisterClientScriptBlock .

http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx

 int[] yourArray = new int[] { 1, 2, 3 }; string arrElements = string.Join(",", yourArray.Select(x => x.ToString()).ToArray()); string strJs = string.Format("var yourArray=[{0}]", arrElements); RegisterClientScriptBlock("Test", strJs); 
+3
source

you need to pass the array on the client side (part of javascript):

I would suggest making an ajax request to the page that will return the serialized array or, as @ Blade0rz suggested, to output the serialized string directly to the page. to serialize the array in JSON format, you would call the JavaScriptSerializer class methods:

more details here

0
source

C # code behind:

 float [] energyArray = new float[count]; public JavaScriptSerializer javaSerial = new JavaScriptSerializer(); 

Try this code:

 <script> var a = <%= this.javaSerial.Serialize(this.energyArray) %>; for (var i = 0; i < a.length; i++) { console.log(a[i]); } </script> 
0
source

Declare HiddenField

  <asp:HiddenField id="myHiddenField" runat="server" 

Set this value for your array. Tostring () in code then in your javascript

  var h = document.getElementById('myHiddenField'); //Should give you an array of strings that you can cast to integers 
0
source

Source: https://habr.com/ru/post/1483549/


All Articles