简体   繁体   中英

Passing Morris Chart data by Viewmodel property with MVC

I am building a Morris Chart based on a database data and I pass to the View using the Viewmodel:

Razor code:

@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}]">

The problem is that the Javascript side can't read the data because it's in string format.

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']
    });

I would like to keep the chart data in the Viewmodel and avoid Javascript in the View, how can I do that?

Thanks.

In your view, serialize the property and set to a javascript variable. This will be JSON.

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

Now you can use the chartData variable in your javascript code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM