asp.net mvc-从控制器到视图到javascript的二维整数数组



我正在处理一个javascript图,它需要以下格式的数据-

data = [[int, int],[int, int], [int, int], ....]

在行动方法中,我有以下代码-

 List<GraphData> data = new List<GraphData>(); // GraphData is a model
 data.Add(new GraphData() { PositionNo =1, Quantity = 10 }); 
 data.Add(new GraphData() { PositionNo =2, Quantity = 20 });
 ViewBag.GraphData= data; //sending to view

我被困在这里了。如何将这些数据从剃须刀发送到javascript数组?

在您的视图中尝试这个

<script type="text/javascript">
   var data = [@Html.Raw(Json.Encode(ViewBag.GraphData))];
</script>

从javascript:调用您的操作方法

public ActionResult GetGraphData()
{
  List<GraphData> data = new List<GraphData>(); // GraphData is a model
  data.Add(new GraphData() { PositionNo =1, Quantity = 10 }); 
  data.Add(new GraphData() { PositionNo =2, Quantity = 20 });
  ViewBag.GraphData= data; //sending to view
 return Json(data, JsonRequestBehavior.AllowGet);
}

脚本:

$.get("/Controller/GetGraphData", function(data) {
    //access data[0].PositionNo
});
var array=[,];
@foreach(var data in ViewBag.GraphData as List<GraphData>)
{
<text>
var d="@data";
array.push(d);
</text>
}
var GraphData=@Html.Raw(Json.Encode(ViewBag.GraphDatas));
var graphData=[];
for (var i = 0; i < GraphData.length; i++) {
    graphData[i]=[];
    graphData[i].push(GraphData[i].PositionNo);
    graphData[i].push(GraphData[i].Quantity);
}

相关内容

  • 没有找到相关文章