0

I create a dictionary in the model, which has The City as Key and The numbers of Kids as Value (@Model.dictionary). I want to make the pie chart dinamically so How can I use the dicionary data instead of the static data in my drawChart function.

I hope you can help me, thanks a lot.

   <html>
    <head>

    </head>
    <body>
        <div id="piechart_3d" style="width: 900px; height: 500px;"></div>

        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);


          function drawChart() {
            var data = google.visualization.arrayToDataTable([
              ['City', 'Kids per Day'],
              ['LA',    100000],
              ['NY',    100000]
            ]);

            var options = {
              title: 'Kids per City',
              is3D: true,
            };

            var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
            chart.draw(data, options);
          }
        </script>
    </body>
    </html>

1 Answer 1

1

You can create a javascript array using razor, using this answer that converts a List to arra,y you can convert from Dictionary very easy:

var array = [@Html.Raw(String.Join(",", Model.dictionary.Select(x => "['" + x.Key + "', '" + x.Value +"']")))];

This will create

[
   ['LA',    100000],
   ['NY',    100000]
]

And you use it like this, with few modifications.

function drawChart() {
    var javaScriptArray = @Html.Raw(Json.Encode(Model.YourDotNetArray));


    var data = google.visualization.arrayToDataTable([
      ['City', 'Kids per Day'],
      @Html.Raw(String.Join(",", Model.dictionary.Select(x => "['" + x.Key + "', '" + x.Value +"']")))
    ]);

    var options = {
      title: 'Kids per City',
      is3D: true,
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.