0
I am trying to pass the data from a list to a viewbag, but it is not returning correctly in the view.
My model and control:
public class DataPoint
{
public String nome = null;
public double y = 0;
public DataPoint(String nome, double y)
{
this.nome = nome;
this.y = y;
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
List<string> nome = new List<string>();
List<double> y = new List<double>();
List<DataPoint> dataPoints = new List<DataPoint>
{
new DataPoint("Casamento",50),
new DataPoint("Óbitos",10),
new DataPoint("Nascimento", 40),
new DataPoint("Rec. de Firma", 40),
new DataPoint("Autenticações", 60)
};
foreach (var item in dataPoints)
{
nome.Add(item.nome);
y.Add(item.y);
}
ViewBag.nome = nome;
ViewBag.valor = y;
return View();
}
And my view:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ChartJS</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js">
</script>
<script>
var DoughnutChartData =
{
labels: [@Html.Raw(ViewBag.nome)],
datasets: [{
label: 'Teste com ChartJS',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#87CEFA",
"#99e5e7",
"#f7bd83",
],
borderWidth: 2,
data: [@ViewBag.valor]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("Doughnutcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'pie',
data: DoughnutChartData,
options:
{
title:
{
display: true,
text: "Teste Chart"
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
The return of the Abels came like this: Labels: ['Marriage', Deaths', Birth', Rec. firm',Authentications'], some are not in single quotes.
– Adriano Praia
@Adrianopraia Oops, I will edit the answer with the correction.
– Leandro Angelo
@Adrianopraia Pronto,
string.Join("','",ViewBag.nome)
– Leandro Angelo
@Adrianopraia Sucesso?
– Leandro Angelo
Yes, Leandro! Now gave good, thank you very much!
– Adriano Praia