3

I am trying to make a Chart with Chart.js but i cant get the data from my model into the chart... can someone help me with this?

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

<canvas id="myChart" width="400" height="400"></canvas>
<script >
var ctx = document.getElementById('myChart').getContext('2d');
@{ 
    List<String> listKeys = new List<string>();
    List<int> listValues = new List<int>();
    foreach(var x in Model.PageViews)
    {
        listKeys.Add(x.Key + "");
        listValues.Add(x.Value);
    }
}

var chart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: @listKeys,
        datasets: [{
            label: "My First dataset",
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: @listValues
        }]
    },
    options: {}
});

I've tried multiple things but nothing seems to work...

1
  • 1
    Your model should contain properties IEnumerable<string> Labels and IEnumerable<int> Values and then you use var labels = @Html.Raw.Json.Encode(Model.Labels)) ect to convert the model to a javascript array Commented Nov 20, 2018 at 9:52

2 Answers 2

4

The code inside block @{ } is server side. Other content of the script-tag is client side.

C# runs ToString() method when you use @listKeys/@listValues. It generates string like System.Collections.Generic.List[System.String] instead of content of the lists. You need to generate json objects instead.

Use @Html.Raw(Json.Serialize(listKeys)) instead of @listKeys to get correct json-object with data.

P.S. It's not good practice to use a lot of server-logic inside views. You can remove your @{} block and get json for Model.PageViews.Keys and Model.PageViews.Values

Sign up to request clarification or add additional context in comments.

Comments

0

It's not good practice to use .NET variables in JavaScript code. The right way is to create hidden html elements for values who you want to use in js function or use API that returns chart data as Json object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.