Miguel Cordero
Miguel Cordero

Reputation: 141

Importing data from Model into a View gives me an error I cannot solve

I have a model:

public class ReportViewModel
{
    public int[] Data { get; set; }
    public string[] Labels { get; set; }
}

Then, in the controller I get the data and labels, and save it on the model which will be sent to the view:

[HttpGet]
    public async Task<IActionResult> Report()
    {

        ReportingViewModel vm = new ReportingViewModel();
        vm.Data = DataReporting(vm);
        vm.Labels = LabelReporting(vm);
        return View(vm);
    }

The arrays are created perfectly, because I have debugged and are just what I want.

Then I pass them to the view into a Chart.js graph through @Model.Data, but I get an error on the console and the graph is not displayed.

<div id="container" class="align-items-center" style="width:75%; margin: 0 auto" ;>
    <canvas id="myChart" width="682" height="340"></canvas>
    <script>
        var colorbarra = Array(78).fill('rgba(54, 162, 235, 0.2)');
        var colorborde = Array(78).fill('rgba(54, 162, 235, 1)');
        var datos = @Model.Data;
        var etiquetas = @Model.Labels ;
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: etiquetas,
                datasets: [{
                    label: 'Nº de Custodios subidos',
                    data: datos,
                    backgroundColor: colorbarra,
                    borderColor: colorborde,
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    </script>
</div>

This is the error I get on the console: Error on console

Reporting:188 Uncaught SyntaxError: Unexpected token ]

And line 188 is the line related to @Model.Data

var datos = System.Int32[];

Thank you very much in advance.

Upvotes: 3

Views: 80

Answers (3)

er-sho
er-sho

Reputation: 9771

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));

Upvotes: 1

N babin
N babin

Reputation: 1

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

Upvotes: 0

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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.

Upvotes: 1

Related Questions