我正在根据数据库数据构建Morris图表,并使用Viewmodel传递给View:
剃刀代码:
@Html.HiddenFor(m => m.SurveyLastDaysChartData)
HTML code:
<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,我该怎么做?
感谢。
答案 0 :(得分:3)
在您的视图中,序列化属性并设置为javascript变量。这将是JSON。
<script>
var chartData = @Html.Raw(Newtonsoft.Json.JsonConvert
.SerializeObject(Model.SurveyLastDaysChartData));
</script>
现在,您可以在JavaScript代码中使用chartData
变量。
答案 1 :(得分:1)
variant[0].price