列表<T>到Javascript数组

List<T> to Javascript array

本文关键字:Javascript 数组 lt 列表 gt      更新时间:2023-09-26

我定义了以下类

public ReportsViewmodel
{
    public GeographicData GeographicData { get; set; }
    ...
}
public class GeographicData
{
    public List<ZipcodeData> Regions { get; set; }
    ...
}
public class  ZipcodeData
{
     //TupleList is defined as public class TupleList<T1, T2> : List<Tuple<T1, T2>>
     public TupleList<double, double> Boundries { get; set; }//Contains list of Lat/Long values for plotting on a map.         
}

在我看来,我需要做这样的事情:

foreach (region in GeographicData.Regions)
    foreach (boundry in region.Boundries)
       add item1 & item2 to a 2 dimensional Javascript array

最后,我希望我的javascript数组看起来像:

var vmBoundries= [[34.1, -85.4], [34.8, -85.234], [34.347, -85.345], [34.541, -85.434], [34.2341, -85.4]];

我不知道如何从我的视图中访问数据。我不断遇到范围问题。例如,如果我尝试使用javascript For循环,我就无法索引到ViewModel列表中,因为当我调用@Model.GeographicData.Regories[I]…时,循环变量是未定义的

那么,如何将ViewModel中的数据拉入Javascript数组呢?

通常您会:

  1. 将数据转换为所需格式
  2. 将转换后的数据序列化为JSON
  3. 为序列化的值分配一个JavaScript变量

所以,像这样的东西:

@{
    IEnumerable<double[]> flattened = vm.GeographicData.Regions
        .SelectMany(region => region.Boundries
            .Select(tpl => new double[] { tpl.Item1, tpl.Item2 }));
    string json = new JavaScriptSerializer().Serialize(flattened);
}
<script type="text/javascript">
    var arr = @json;
    // do something with arr.
</script>

类似于:

    var array = (from region in GeographicData.Regions
            select from boundry in region.Boundries
                 select new object[] { boundry.Item1, boundry.Item2 }).ToArray();

这将为您提供一个2D数组,然后您可以对其进行序列化。

示例:https://dotnetfiddle.net/Y9KOaq

我会使用javascript序列化程序来简化它:

using System.Web.Script.Serialization;

并在ReportsViewmodel:中添加一个helper方法

public string GetBoundriesJs()
{
    var pairs =
        from r in GeographicData.Regions
        from b in r.Boundries
        select new[] { b.Item1, b.Item2 };
    return new JavaScriptSerializer().Serialize(pairs);
}

然后你可以把它称为你认为需要的地方:

var vmBoundries = @Model.GetBoundriesJs();