[Chartjs]-Importing data from Model into a View gives me an error I cannot solve

1πŸ‘

βœ…

If you want to use view models properties to javascript then you need convert it like,

var datos = JSON.stringify(@Model.Data);
var etiquetas = JSON.stringify(@Model.Labels);

Or you can use

var datos = @Html.Raw(Json.Serialize(@Model.Data));
var etiquetas = @Html.Raw(Json.Serialize(@Model.Labels));

1πŸ‘

To pass server-side array into client-side array variable, you can use client-side JSON.parse() function with Json.Encode():

var datos = JSON.parse(@Html.Raw(Json.Encode(Model.Data));
var etiquetas = JSON.parse(@Html.Raw(Json.Encode(Model.Labels));

Or if you have Newtonsoft.Json package, you should try using JsonConvert.SerializeObject() method:

var datos = JSON.parse(@Html.Raw(JsonConvert.SerializeObject(Model.Data));
var etiquetas = JSON.parse(@Html.Raw(JsonConvert.SerializeObject(Model.Labels));

If the array is passed directly like @Model.Data, ToString() will implicitly called which causing fully-qualified name of the array type to be assigned instead of serialized array contents.

0πŸ‘

As shiwn in documentation of chart.js here is link for documentation of chart.js you must give dataset and lable in array format.

Try using passing ienumerable for passing model to view which will implict convert into array.
Your class must like this

public class ReportViewModel { 
   public innumerable<data> cData { get; set; } 
   public innumerable<label> cdata { get; set; }
}

And your class for data and label must be defined in model namespace
Data model:

Public class data{
    Public int value{get;set;}
}

Label model

Public class label{
    Public string name{get;set;}
}

And in view you have to import model which must must be passed from controller and you can directly use that and using razor engine you can convert it also into array at runtime using toarray function

Leave a comment