2016-07-18 57 views
0

我建立一個莫里斯圖表基於數據庫的數據和我通過使用視圖模型視圖:通過視圖模型屬性傳遞莫里斯圖表數據與MVC

剃刀代碼:

@Html.HiddenFor(m => m.SurveyLastDaysChartData) 

HTML代碼:

<input id="SurveyLastDaysChartData" name="SurveyLastDaysChartData" type="hidden" value="[{"Date":"2016-07-18","Average":0},{"Date":"2016-07-17","Average":0},{"Date":"2016-07-16","Average":0},{"Date":"2016-07-15","Average":4.125},{"Date":"2016-07-14","Average":0},{"Date":"2016-07-13","Average":0},{"Date":"2016-07-12","Average":0}]"> 

的問題是,JavaScript端無法讀取數據,因爲它是字符串格式。

var _surveyLastDaysChartId = "dsb-survey-last-days-chart"; 
var _surveyLastDaysChartData = $("#SurveyLastDaysChartData"); 

Morris.Line({ 
     // ID of the element in which to draw the chart. 
     element: _surveyLastDaysChartId, 
     // Chart data records -- each entry in this array corresponds to a point on the chart. 
     data: _surveyLastDaysChartData.val(), 
     // The name of the data record attribute that contains x-values. 
     xkey: 'Date', 
     // A list of names of data record attributes that contain y-values. 
     ykeys: ['Average'], 
     // Labels for the ykeys -- will be displayed when you hover over the chart. 
     labels: ['Value'] 
    }); 

我想保留ViewModel中的圖表數據並避免在View中使用Javascript,我該怎麼做?

謝謝。

回答

2

在您的視圖中,序列化屬性並設置爲一個JavaScript變量。這將是JSON。

<script> 
var chartData = @Html.Raw(Newtonsoft.Json.JsonConvert 
             .SerializeObject(Model.SurveyLastDaysChartData)); 
</script> 

現在您可以在您的JavaScript代碼中使用chartData變量。

+0

嗨,謝謝。我可以在視圖中避免使用JavaScript嗎? – Patrick

+1

在這種情況下,您需要傳遞模型數據。所以你需要在你的剃刀視圖中有這條線(因爲它使用的是C#代碼) – Shyju

+0

在你看來,我正在做的這件事? – Patrick

1
data : @(Html.Raw(System.Web.Helpers.Json.Encode(Model.ListOfYouNeed))) 
+0

嗨,謝謝!對不起,我已經檢查Shyju的回答是否正確,因爲他已經回覆了第一個。 – Patrick