如何从C#发送我的价值观的JavaScript与asp.net [英] How do I send my values from c# to javascript with asp.net

查看:96
本文介绍了如何从C#发送我的价值观的JavaScript与asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数组这样一个简单的C#功能:

I have a simple c# function that returns an array like this:

protected int[] numArray()
{
    int [] hi = {1,2};
    return hi;
}

我试图让这些值到我的javascript,所以我想这样做在asp.net:

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

然而,代替传递数组背面,它似乎传递字符串(System.Int32 [])。第一个警报打印一个S和第二打印一个Y。如何打印我的号码来代替。我必须从我的C#code返回一个字符串?

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?

推荐答案

您需要序列化数组JSON。做到这一点的方法之一是使用的JavaScriptSerializer ...

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

这篇关于如何从C#发送我的价值观的JavaScript与asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆