将 C# 数组传递给 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14942385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:59:48  来源:igfitidea点击:

Pass C# Array To Javascript

c#javascriptasp.netarrays

提问by TheChampp

What is the best way to pass C# array to javascript variable ?

将 C# 数组传递给 javascript 变量的最佳方法是什么?

I have sample code but this return character by character from C# array, I want to return in normal way like word by word in javascript array;

我有示例代码,但是这个从 C# 数组中逐个字符地返回,我想以正常方式返回,例如在 javascript 数组中逐字返回;

C# code behind:

后面的 C# 代码:

 public string[] names = { "John", "Pesho", "Maria"};
 public JavaScriptSerializer javaSerial = new JavaScriptSerializer();

javascript code:

javascript代码:

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

This script return all words from "names" array in single char array . I want to return in normal way like ["John"] ["Pesho"] ...

此脚本以单个字符数组的形式返回“名称”数组中的所有单词。我想以正常的方式返回,例如 ["John"] ["Pesho"] ...

What is the best way to pass C# array to javascript ?

将 C# 数组传递给 javascript 的最佳方法是什么?

When I run this code I get the following in console of Chrome browser:

当我运行此代码时,我在 Chrome 浏览器的控制台中得到以下信息:

[ Profile.aspx:44
" Profile.aspx:44
v Profile.aspx:44
a Profile.aspx:44
l Profile.aspx:44
e Profile.aspx:44
r Profile.aspx:44
i Profile.aspx:44
" Profile.aspx:44
, Profile.aspx:44
" Profile.aspx:44
p Profile.aspx:44
e Profile.aspx:44
s Profile.aspx:44
h Profile.aspx:44
o Profile.aspx:44
" Profile.aspx:44
, Profile.aspx:44
" Profile.aspx:44
m Profile.aspx:44
a Profile.aspx:44
r Profile.aspx:44
i Profile.aspx:44
a Profile.aspx:44
" Profile.aspx:44
] 

回答by Matthew

Replace

代替

var a = '<%= this.javaSerial.Serialize(this.names) %>';

with

var a = <%= this.javaSerial.Serialize(this.names) %>;

You were putting the resulting JSON into a javascript string, which would result in your example output iterating through each character of the Serializecall.

您将生成的 JSON 放入一个 javascript 字符串中,这将导致您的示例输出遍历Serialize调用的每个字符。

回答by hnafar

your c# code will return a string, you have to first parse the string using JSON.parse, and then iterate through it:

您的 c# 代码将返回一个字符串,您必须首先使用 JSON.parse 解析该字符串,然后对其进行迭代:

var a = JSON.parse('<%= this.javaSerial.Serialize(this.names) %>');
for (var i = 0; i < a.length; i++) {
    console.log(a[i]);
}

or maybe as @Matthew said, don't put quotes around it, so you won't have to parse it.

或者正如@Matthew 所说,不要在它周围加上引号,这样你就不必解析它。