【问题标题】:Passing Morris Chart data by Viewmodel property with MVC使用 MVC 通过 Viewmodel 属性传递莫里斯图数据
【发布时间】:2016-07-18 15:41:47
【问题描述】:

我正在基于数据库数据构建莫里斯图,并使用 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 中并避免在 View 中使用 Javascript,我该怎么做?

谢谢。

【问题讨论】:

    标签: javascript c# asp.net-mvc morris.js


    【解决方案1】:

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

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

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

    【讨论】:

    • 这种情况下,需要传递模型数据。所以你需要在你的 razor 视图中有这一行(因为它使用 C# 代码)
    • 是的。在这个用例中,拥有它就很好。
    • 最后一件事,在控制器上序列化更好还是喜欢你的答案? model.SurveyLastDaysChartData = jsonSerializer.Serialize(chartData);
    • 您希望在客户端 javascript 变量中使用它。礼?然后你应该在你的剃刀视图中这样做。
    • 非常感谢您的帮助;)
    【解决方案2】:
    data : @(Html.Raw(System.Web.Helpers.Json.Encode(Model.ListOfYouNeed)))
    

    【讨论】:

    • 您好,谢谢!抱歉,我已经检查了 Shyju 的答案是否正确,因为他先回复了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多