简体   繁体   English

动态创建带有 C# 代码的 javascript 数组

[英]Dynamically create javascript array with c# code behind

I am updating an old classic ASP site to a new .net 3.5 version.我正在将旧的经典 ASP 站点更新为新的 .net 3.5 版本。 The page has a custom list control which the client (my boss) wants to keep.该页面有一个客户(我的老板)想要保留的自定义列表控件。 This list control requires several arrays in order to work correctly.此列表控件需要多个数组才能正常工作。 the array is a multi-dimensional list of publications.该数组是一个多维出版物列表。 This is what it looks like:这是它的样子:

var publicationTable = [
    [31422,"Abilene Reporter News","Abilene","TX",false,"D",0],
    [313844,"Acadiana Weekly","Opelousas","LA",false,"W",1],
    [527825,"Action Advertiser","Fond du Lac","WI",false,"W",2]...n]

I want to generate this array server side and register it.我想生成这个数组服务器端并注册它。 I have looked at the msdn but this is a little trivial.我看过msdn,但这有点微不足道。 The conceptual issue is that the array is a mixture of string and ints and I am not sure how to recreate this, so how?概念上的问题是数组是字符串和整数的混合体,我不确定如何重新创建它,那么如何呢?

You should do this:你应该做这个:

Code behind:后面的代码:

using System.Web.Script.Serialization;
...
public string getJson(){
   var publicationTable = new List<object>{
      new []{ 31422,"Abilene Reporter News","Abilene","TX",false,"D",0},
      new []{ 313844,"Acadiana Weekly","Opelousas","LA",false,"W",1 },
      new []{ 527825,"Action Advertiser","Fond du Lac","WI",false,"W",2}
   };
   return (new JavaScriptSerializer()).Serialize(publicationTable);
}

Ase you see, to create an array of mixed types, we create an array of anonymous type with new [] .如您所见,要创建混合类型数组,我们使用new []创建了一个匿名类型数组。 You could also have done it with new object[] .你也可以用new object[]

Aspx file: Aspx文件:

<script>
    var publicationTable = <%= getJson() %>;
</script>

Hope this helps.希望这可以帮助。 Cheers干杯

I think a List<List<object>> containing your items, passed through the JavaScriptSerializer would do the trick.我认为一个List<List<object>>包含您的项目, 通过JavaScriptSerializer传递就可以了。 Given that this data probably comes from a more structured data type, you could probably do better than List<List<object>> , but the JavaScriptSerializer is probably what you're after.鉴于此数据可能来自更结构化的数据类型,您可能会比List<List<object>>做得更好,但JavaScriptSerializer可能正是您所追求的。

Will this work?这会起作用吗?

ArrayList list = new ArrayList{31422,"Abilene Reporter News","Abilene","TX",false,"D",0};

var str = string.Format("[{0}]", list.Cast<object>().Select(x => (x is string)?
          string.Format(@"""{0}""", x) : x.ToString())
          .Aggregate((x, y) => string.Format("{0}, {1}", x, y)));

it can be extended for a multi-dimensional array in a similar fashion.它可以以类似的方式扩展到多维数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM