smaica
smaica

Reputation: 817

Access data arrays from c# method inside JavaScript inside .cshtml file

I'm new to web page creation so I'm facing some problems with communication between backend and frontend. Currently, I want to show a simple chart (I'm using chart.js for that) with data that I calculate in a separate c# method.

My c# method looks like this:

using System;
using System.Linq;

namespace Programm.Logic
{
    public class DoSomethingIntelligent
    {    
        public int[] GetRandomData(int number)
        {
            int Min = 0;
            int Max = 20;
            Random randNum = new Random();
            int[] data = Enumerable
                .Repeat(0, number)
                .Select(i => randNum.Next(Min, Max))
                .ToArray();

            return data;
        }
    }
}

Now I create a chart insige of my .cshtml file. Up to now the data is hardcoded but I would like to create the data with the method above (GetRandomData()). How do I do this? I tried:

@Model.GetRandomData(6);

but this gives the output of "System.Int32[]". Even if this would work, I would not knot how to parse this data to the chart. My .cshtml file looks like this:

@model Programm.Logic.DoSomethingIntelligent

<!DOCTYPE html>

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <title>My Chart.js Chart</title>
</head>

<body>

    <div class="container">
        <canvas id="myChart"></canvas>
    </div>

    <script>
        let myChart = document.getElementById('myChart').getContext('2d');

        let thisChart = new Chart(myChart, {
            type: 'bar', // bar, horizontalBar, pie, line, doughnut, radar, polarArea
            data: {
                labels: ['1', '2', '3', '4', '5', '6'],
                datasets: [{
                    label: 'test',
                    data: [
                        617594,
                        181045,
                        153060,
                        106519,
                        105162,
                        95072
                    ]
                }]
            }
        });

    </script>


</body>
</html>

Big thanks!

Upvotes: 0

Views: 632

Answers (1)

Shyju
Shyju

Reputation: 218832

but when I try to print out @Model.GetRandomData(6) it shows "System.Int32[]"

You will get something like above mentioned when you try code like this.

var data = @Model.GetRandomData(6);

Razor is going to render the output like below if you check the view source of the page.

 var data = System.Int32[];

This happens because your GetRandomData method returns an int array and when razor is trying to execute your C# code, it is basically calling the ToString() which is returning the type.

If you want to get the array generated by your C# method to JavaScript array, you need to Serialize the output of the method.

The below should work.

var data = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.GetRandomData(6)));
let myChart = document.getElementById('myChart').getContext('2d');

let thisChart = new Chart(myChart, {
    type: 'bar', 
    data: {
        labels: ['1', '2', '3', '4', '5', '6'],
        datasets: [{
            label: 'test',
            data: data
        }]
    }
});

Upvotes: 1

Related Questions