Pass data to viewbag from controller to view using Chart.JS

Asked

Viewed 517 times

0

I am trying to pass the data from a list to a viewbag, but it is not returning correctly in the view.

inserir a descrição da imagem aqui

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>

1 answer

0


You are forgetting to format the result as expected and are printing only the object. Note that for the List<double> I added a treatment to preserve separation by "." otherwise it would be replaced by "," and its array would not be written correctly.

@{
    var valorArray = (List<double>)ViewBag.valor;
}
    var DoughnutChartData =
            {
                labels:  [@Html.Raw("'" + string.Join("','",ViewBag.nome) + "'")],
                datasets: [{
                    label: 'Teste com ChartJS',
                    backgroundColor: [
                        "#f990a7",
                        "#aad2ed",
                        "#87CEFA",
                        "#99e5e7",
                        "#f7bd83",
                    ],
                    borderWidth: 2,
                    data: [@Html.Raw(string.Join(",",valorArray.Select(x => x.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray()))]
                }]
            };
  • The return of the Abels came like this: Labels: ['Marriage', Deaths', Birth', Rec. firm',Authentications'], some are not in single quotes.

  • @Adrianopraia Oops, I will edit the answer with the correction.

  • @Adrianopraia Pronto, string.Join("','",ViewBag.nome)

  • @Adrianopraia Sucesso?

  • Yes, Leandro! Now gave good, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.