2012-07-30 62 views
1

我使用一個ViewModel如下創建系列:在HighCharts使用JSON

namespace AESSmart.ViewModels 
{ 
    public class HighChartsPoint 
    { 
    public double x { set; get; } 
    public double y { set; get; } 
    public string color { set; get; } 
    public string id { set; get; } 
    public string name { set; get; } 
    } 

    public class HighChartsSeries 
    { 
    public List<HighChartsPoint> data { set; get; } 
    public string name { set; get; } 
    public string type { set; get; } 
    } 

    public class HomeIndexViewModel 
    { 
    public string HCSeries {get;set;} 

    public void setChartData() 
    { 
     List<HighChartsSeries> allSeries = new List<HighChartsSeries>(); 
     List<HighChartsPoint> allPoint = new List<HighChartsPoint>(); 

     allPoint.Add(new HighChartsPoint { x = 49.9, y = 1 }); 
     allPoint.Add(new HighChartsPoint { x = 71.5, y = 2 }); 
     allPoint.Add(new HighChartsPoint { x = 106.4, y = 3 }); 
     allPoint.Add(new HighChartsPoint { x = 129.2, y = 4 }); 

     allSeries.Add(new HighChartsSeries { 
     data = new List<HighChartsPoint>(allPoint), 
     name = "Series 1", 
     type = "column" 
     }); 

     JavaScriptSerializer oSerializer = new JavaScriptSerializer(); 
     HCSeries = oSerializer.Serialize(allSeries); 
    } 
    } 
} 

然後在我看來,我設置了series: @Model.HCSeries像這樣:

@section HeadContent { 
    <script type="text/javascript"> 
    var chart; 
    $(document).ready(function() { 
     chart = new Highcharts.Chart({ 
     chart: { 
      renderTo: "container4", 
      type: "column", 
     }, 
     series: @Model.HCSeries 
     }); 
    }); 
    </script> 
} 

當我運行程序它不顯示HighChart。如果我看視圖源,它看起來像這樣:

<script type="text/javascript"> 
    (function ($) { // encapsulate jQuery 
    var chart; 
     $(document).ready(function() { 
     chart = new Highcharts.Chart({ 
      chart: { 
      renderTo: 'container4', 
      type: 'column' 
      }, 
      series: [[{&quot;data&quot;:[ 
      {&quot;x&quot;:49.9,&quot;y&quot;:1,&quot;color&quot;:null,&quot;id&quot;:null,&quot;name&quot;:null}, 
      {&quot;x&quot;:71.5,&quot;y&quot;:2,&quot;color&quot;:null,&quot;id&quot;:null,&quot;name&quot;:null}, 
      {&quot;x&quot;:106.4,&quot;y&quot;:3,&quot;color&quot;:null,&quot;id&quot;:null,&quot;name&quot;:null}, 
      {&quot;x&quot;:129.2,&quot;y&quot;:4,&quot;color&quot;:null,&quot;id&quot;:null,&quot;name&quot;:null}], 
      &quot;name&quot;:&quot;Series 1&quot;, 
      &quot;type&quot;:&quot;column&quot;}]] 
     }); 
     }); 
    })(jQuery); 
</script> 

如果我手動直接輸入數據到視圖然後圖表確實顯示。但是,我將需要動態創建系列。 我需要做些什麼來修復我的代碼,以便圖表顯示?

回答

1

我認爲這是因爲您的序列化JSON包含&quot;而不是"

試試這個:

HCSeries = @Html.Raw(oSerializer.Serialize(allSeries)); 
+0

嘿,你讓我在正確的軌道上。我不得不修改我在視圖中創建HighChart的方式。我編輯了上面的代碼來顯示我改變了什麼。然後,我應用以下內容在視圖中設置系列:@ Html.Raw(Model.HCSeries)'。現在一切正常顯示。 – Linger 2012-07-31 17:52:26