我定义了以下类
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.Regions [i] ...时,循环变量是未定义的。
那么如何将我的ViewModel中的数据提取到Javascript数组中呢?
答案 0 :(得分:1)
通常你会:
所以,像这样:
@{
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>
答案 1 :(得分:0)
类似的东西:
var array = (from region in GeographicData.Regions
select from boundry in region.Boundries
select new object[] { boundry.Item1, boundry.Item2 }).ToArray();
这将为您提供一个2D数组,然后您可以将其序列化。
答案 2 :(得分:0)
我会使用javascript序列化程序来简化:
using System.Web.Script.Serialization;
并向ReportsViewmodel
添加辅助方法:
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();