通过C#阵列为Javascript [英] Pass C# Array To Javascript

查看:93
本文介绍了通过C#阵列为Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是通过C#数组JavaScript变量的最佳方式?

我有样code,但由C#字符数组这个返回的性格,我想以正常的方式就像一个字一个字的JavaScript数组中返回;

C#code背后:

 公共字符串[] =名称{约翰,Pesho,玛丽亚};
 公众的JavaScriptSerializer javaSerial =新的JavaScriptSerializer();

JavaScript的code:

 <脚本>
    VAR一个='<%= this.javaSerial.Serialize(this.names)%GT;';
    对于(VAR I = 0; I<则为a.length;我++){
        的console.log(A []​​);
    }
 < / SCRIPT>

本脚本单字符数组名字数组返回所有单词。我想在正常的方式返回如[约翰] [Pesho] ...

什么是通过C#数组的JavaScript的最好方法?

当我运行这个code,我得到的Chrome浏览器的控制台以下内容:

  [Profile.aspx:44
Profile.aspx:44
v Profile.aspx:44
一个Profile.aspx:44
升Profile.aspx:44
ËProfile.aspx:44
- [R Profile.aspx:44
我Profile.aspx:44
Profile.aspx:44
,Profile.aspx:44
Profile.aspx:44
p Profile.aspx:44
ËProfile.aspx:44
小号Profile.aspx:44
^ h Profile.aspx:44
ØProfile.aspx:44
Profile.aspx:44
,Profile.aspx:44
Profile.aspx:44
米Profile.aspx:44
一个Profile.aspx:44
- [R Profile.aspx:44
我Profile.aspx:44
一个Profile.aspx:44
Profile.aspx:44
]


解决方案

替换

  VAR一个='<%= this.javaSerial.Serialize(this.names)%GT;';

  VAR一个=<%= this.javaSerial.Serialize(this.names)%取代;

您是把生成的JSON转换为JavaScript字符串,这将导致通过序列化呼叫的每个字符的示例输出迭代。

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

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# code behind:

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

javascript code:

 <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"] ...

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

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

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

解决方案

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 Serialize call.

这篇关于通过C#阵列为Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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