将c#数组传递给javascript

时间:2013-05-30 10:18:01

标签: c# javascript asp.net json

我在c#中的page_load中有一个数组,我希望在java脚本中访问但不知道如何操作..

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

现在我想用javascript代替数据访问

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]
}]       

5 个答案:

答案 0 :(得分:7)

一种非常简单的方法是使用JavaScriptSerializer类将C#对象转换为JSON:

<强> C#

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
        }];

答案 1 :(得分:3)

在这里改变你的问题...

考虑构建整个javascript字符串块,然后使用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);

答案 2 :(得分:0)

你需要以某种方式将数组传递给客户端(以javascript部分):

我建议对页面发出ajax请求,这将返回序列化数组或@ Blade0rz建议,将序列化字符串直接输出到页面。要将数组序列化为JSON格式,您可以调用JavaScriptSerializer类的方法:

更多信息here

答案 3 :(得分:0)

C#代码背后:

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

试用此代码:

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

答案 4 :(得分:0)

声明一个HiddenField

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

将其值设置为后面代码中的array.Tostring() 然后在你的javascript

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