Chartjs-Take input values and pass it into javascript function for Chart.js chart in ASP.NET core Razor Pages

0👍

Needed to create new variable lists in Javascript part and then used .slice() on them.

See updated code:

@page
@model statmath_web.Pages.Visualization.VisualizationMainModel
@{
    ViewData["Title"] = "CSV Data Visualization";
}

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

<html>
<head>

</head>
<body>
<center>

    <td >
        <input class="text-center param-input" id="Minimum_Parameter"
        type="number" min="0" max="@Model.length" step="1"
        placeholder="Min" value="0" /> 
    </td>

    <td>
        <input class="text-center param-input" id="Maximum_Parameter"
        type="number" min="0" max="@Model.length" step="1"
        placeholder="Max" value="@Model.length"/>
    </td>

    <br />

    <button onclick="clickupdate()">Update Data</button>

    <canvas id="myChart" width="1200" height="700"></canvas>

<script>
    var ctx = document.getElementById("myChart").getContext("2d");

    var TimestampList = @Html.Raw(Json.Serialize(Model.TimeList));
    var ValueList = @Html.Raw(Json.Serialize(Model.ValueList));

    var myChart = new Chart(ctx, {
        type: "line",
        data: {
            labels: TimestampList,
            datasets: [
                {
                    label: "VSE Value",
                    backgroundColor: "rgb(255, 255, 255)",
                    borderColor: "rgb(54, 162, 235)",
                    fill: false,
                    data: ValueList,
                }
            ]
        },
      options: {
        animation: false,
        parsing: false,
        responsive: true,
      },
    });


    function addData(chart, label, data) {
    chart.data.labels = label
    chart.data.datasets.forEach((dataset) => {
        dataset.data = data;
    });
    chart.update();
}

    function clickupdate(){
        var pMin = document.getElementById('Minimum_Parameter').value;
        var pMax = document.getElementById('Maximum_Parameter').value;
        labelsNew = TimestampList.slice(pMin, pMax);
        dataNew = ValueList.slice(pMin, pMax);
        addData(myChart, labelsNew, dataNew);
    }

</script>

</center>
</body>

</html>

Leave a comment