I need assistance with creating a dynamic chart in my view. The chart should be based on a value entered by the user in an input field within a form. I am using Ajax and Json to handle this asynchronously. After sending the user input to the controller, my code generates two arrays: one string array for the chart labels and another int array for the data values.
My problem is that I can only send one of these arrays at a time and cannot figure out how to send both. I have read suggestions about sending the arrays as a collection, but I'm unsure if this is the correct approach.
Here is a simplified version of the code in my controller:
public ActionResult DoChart(string data)
{
string[] product = {"Bread", "Milk", "Eggs", "Butter"};
int[] quant = {10, 20, 30, 40};
return Json(product, JsonRequestBehavior.AllowGet);
}
Below is the Javascript code in my View:
<script>
$(function() {
$("form#chartForm").on("submit", function(e) {
e.preventDefault();
let obj = {
quantity: $("#quantity").val()
};
$.ajax({
url: "@Url.Action('DoChart')",
method: "GET",
data: {
data: JSON.stringify(obj)
},
success: function(product, status) {
alert(product);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: product,
datasets: [{
label: '# of Votes',
data: [1,2,3,4,5,6,7,8],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
});
});
});
</script>
In the code above, I am currently sending the product array to set the chart labels. However, I want to also send the quant array to set the data values for the chart.
Any help or suggestions would be greatly appreciated. Thank you!