2014-10-09 28 views
1

我在我的MVC 5應用程序中使用JQuery Flot Charts http://www.flotcharts.org/。我想創建水平條形圖和本教程是有幫助的http://www.jqueryflottutorial.com/how-to-make-jquery-flot-horizontal-bar-chart.html將Json數據傳遞給MVC Razor視圖

在圖表插件使用,以創建圖表

var rawData = [[1582.3, 0], [28.95, 1], [1603, 2], [774, 3], [1245, 4], [85, 5], [1025, 6]]; 
var dataSet = [{ label: "Precious Metal Price", data: rawData, color: "#E8E800" }]; 
var ticks = [[0, "Gold"], [1, "Silver"], [2, "Platinum"], [3, "Palldium"], [4, "Rhodium"], [5, "Ruthenium"], [6, "Iridium"]]; 

我的圖表然而數據下面的3行代碼通的,不能使用上面的硬編碼值,而傳遞到我的圖表中的數據需要是動態的。我可以在我的MVC Razor視圖中使用Ajax調用將數據傳遞到rowData變量,該變量調用返回Json的Controller Action(參見下文)。

$.ajax({ 
      type: "GET", 
      contentType: 'application/json; charset=utf-8', 
      dataType: 'json', 
      url: '/Statistics/GetTestData/', 
      error: function() { 
       alert("An error occurred."); 
      }, 
      success: function (data) { 

      var rawData = [data]; 
      } 

}); 

我的問題是我怎樣才能將我的控制器行爲中的數據傳遞給ticks變量?

我想什麼,我需要知道的是,我可以從我的控制器行動兩組數據,一個返回該rawData變量的

[[1582.3, 0], [28.95, 1], [1603, 2], [774, 3], [1245, 4], [85, 5], [1025, 6]] 

格式,其次爲ticks變量中格式

[[0, "Gold"], [1, "Silver"], [2, "Platinum"], [3, "Palldium"], [4, "Rhodium"], [5, "Ruthenium"], [6, "Iridium"]] 

希望這是有道理的。

任何意見或建議,將不勝感激。

謝謝。

回答

3

從我的控制器動作返回兩組數據

。當然,作爲一個複合模型。該行爲只返回一件事,但該事件可以是一個擁有多個屬性的模型。我不知道你的對象結構,而是一個人爲的模型可能看起來像:

public class ChartViewModel 
{ 
    public RawDataModel RawData { get; set; } 
    public TicksModel Ticks { get; set; } 
} 

那麼你的控制器動作將只返回者的一個實例:

var model = new ChartViewModel 
{ 
    RawData = GetRawData(), 
    Ticks = GetTicks() 
}; 
return Json(model); 

這種複合模式就成爲一種方便以包含其他客戶端代碼或與此相關的其他視圖可能需要的其他屬性或行爲。

然後在您的客戶端代碼基於這些特性,你會設置的值:

success: function (data) { 
    var rawData = data.RawData; 
    var ticks = data.Ticks; 
    // etc. 
} 
+0

由於大衛。很好的答案。這在我的應用程序中很好地工作。 – tgriffiths 2014-10-09 15:35:58

1

你需要這樣的

public JsonResult SomeController() 
{ 
    var rawData = rawEnumerable.Select(x => new[] { x.First, x.Second }).ToArray(); 
    var ticks = ticksEnumerable.Select(x => new[] { x.First, x.Second }).ToArray(); 
    retu Json(new{ Ticks = ticks ,RawData = rawData }); 
} 
+0

感謝您的幫助。 – tgriffiths 2014-10-09 15:35:32

0

控制器代碼,您也可以雙擊包裹它在列表( List<List<object>>)並返回它 - 將會很好地映射到flot

實施例:

var grouped = 
result.GroupBy(o => o.USER_ID).Select(agent => new 
{ 
    data = new List<List<object>> 
    { 
     new List<object> 
     { 
      agent.Key, 
      agent.Count() 
     } 
    }, 
    color = "#84d455" 
}).ToList(); 

return Json(grouped, JsonRequestBehavior.AllowGet); 

然後在JS:

function onCancellationAgentsReceived(series) { 
     $("#agentcancellations").empty(); 
     $.plot("#agentcancellations", series, { 
      bars: { show: true, barWidth: 0.7, align: "center" }, xaxis: {mode: "categories", tickLength: 0, position: "bottom"}}); 
    } 
相關問題