0

I pass a C# 2D Array in a ViewBag to my View and I would like to parse it in a Javascript 2D array to use it as a source for a google chart. I have tried:

 var tab = @Html.Raw(@ViewData["tabComplet"]);
 var data = google.visualization.arrayToDataTable(tab);

But it doesn't work, does somebody have an idea ?

6
  • 1
    possible duplicate of Pass C# ASP.NET array to Javascript array Commented Sep 19, 2013 at 8:27
  • 2
    or this one, or this one, or this one... Commented Sep 19, 2013 at 8:29
  • Nothing, it shows me an error "Unexpected token ," in a jquery file so it means that the array is not valid to be used as a source of a google chart Commented Sep 19, 2013 at 8:30
  • That is what your console says, your HTML source (View Source) will show something, even if it is not valid javascript Commented Sep 19, 2013 at 8:30
  • By the way, ViewBag and ViewData are not the same thing Commented Sep 19, 2013 at 8:33

1 Answer 1

0

Find whole project on GitHub or watch the youtube video

In controller, add the following code

            // prepare a 2d array in c#
            ArrayList header = new ArrayList { "Task Name", "Hours"};
            ArrayList data1 = new ArrayList {"Work", 2};
            ArrayList data2 = new ArrayList { "Eat", 2 };
            ArrayList data3 = new ArrayList { "Sleep", 2 };
            ArrayList data = new ArrayList {header, data1, data2, data3};
            // convert it in json
            string dataStr = JsonConvert.SerializeObject(data, Formatting.None);
            // store it in viewdata/ viewbag
            ViewBag.Data = new HtmlString(dataStr);            

In _Layout.cshtml, add the Google script

@*google chart*@
<script type="text/javascript" src="https://www.google.com/jsapi">   </script>

And at last, in the view add the below code

<script>    
    var data = JSON.parse('@ViewBag.Data');
    console.log(data);
</script>
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {

        var chartData = google.visualization.arrayToDataTable(data);

        var options = {
            title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(chartData, options);
    }
</script>

<p>Use this area to provide additional information.</p>

i will show chart in there. but the data will come from viewdata instead of calling jQuery Ajax request.
<div id="piechart" style="width: 900px; height: 500px;"></div>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.