使用 MVC 通过 Viewmodel 属性 传递 Morris Chart 数据

Passing Morris Chart data by Viewmodel property with MVC

我正在基于数据库数据构建莫里斯图,并使用 Viewmodel 传递给视图:

剃须刀代码:

@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 中并避免 Javascript 在 View 中,我该怎么做?

谢谢。

在您看来,序列化 属性 并设置为 javascript 变量。这将是 JSON.

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

现在您可以在 javascript 代码中使用 chartData 变量。

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