2012-06-20 101 views
1

我在控制器中傳遞一個數組到一個視圖中的javascript時遇到了一些麻煩。 我正在使用ASP .Net MVC3,我試圖用數據庫中的數據做一些圖表/圖形,我發現HighCharts的JavaScript,並試圖與它合作。從控制器到Javascript傳遞數組

這裏的例子:

$(function() { 
var chart; 
$(document).ready(function() { 
    chart = new Highcharts.Chart({ 
     chart: { 
      renderTo: 'container', 
      plotBackgroundColor: null, 
      plotBorderWidth: null, 
      plotShadow: false 
     }, 
     title: { 
      text: 'Browser market shares at a specific website, 2010' 
     }, 
     tooltip: { 
      formatter: function() { 
       return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; 
      } 
     }, 
     plotOptions: { 
      pie: { 
       allowPointSelect: true, 
       cursor: 'pointer', 
       dataLabels: { 
        enabled: true, 
        color: '#000000', 
        connectorColor: '#000000', 
        formatter: function() { 
         return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; 
        } 
       } 
      } 
     }, 
     series: [{ 
      type: 'pie', 
      name: 'Browser share', 
      data: [ 
       ['Firefox', 45.0], 
       ['IE',  26.8], 
       ['Chrome',  12.8], 
       ['Safari', 8.5], 
       ['Opera',  6.2], 
       ['Others', 0.7] 
      ] 
     }] 
    }); 
}); 

}); 

我做了這個類:

public class RegistoPie 
{ 
    public string na { get; set; } 
    public double da { get; set; } 


    public RegistoPie(string n, double d) { 

     na = n; 
     da = d; 

    } 
} 

我送這個對象的視圖試圖填補在JavaScript中數據變量:

var pie = new [] { new RegistoPie("papa",20.0), new RegistoPie("pepe",50.0) }; 

但它的返回類似於:

[{"na":"papa","da":20},{"na":"pepe","da":50}]; 

所以它不是相同的語法在JavaScript 數據變量,它只有:

[[string,double], [,] , ... ] 

幫助的人? 泰, 埃爾德

在控制器

回答

2

ViewBag.Array = new[] { new RegistoPie("papa", 20.0), new RegistoPie("pepe", 50.0) }; 

在查看:

@{ 
    var myArray = ViewBag.Array as TestMVC.Controllers.RegistoPie[]; 

    for (int i = 0; i < myArray.Length; i++) 
    { 
     var item = myArray[i]; 
    <text> ['@item.na', @item.da] @((myArray.Length - 1) != i ? "," : "")</text> 
    } 
} 
+0

泰:d是非常有益的 –

相關問題