Reputation: 2781
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.
Upvotes: 0
Views: 1002
Reputation: 21
data : @(Html.Raw(System.Web.Helpers.Json.Encode(Model.ListOfYouNeed)))
Upvotes: 1
Reputation: 218792
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.
Upvotes: 3