I need to reuse a JavaScript code that draws a pieChart in an HTML Page with Razor. Now I'm only passng a single DataTable to the view to be rendered as the pieChart, but I want to pass 3 more DataTables without having to repeat 3 times the JavaScript Code.

My Controller:

public ActionResult Dashboard()
            var data = db.SomeDatabaseTable;

            DataTable dt = new DataTable();

            dt.Columns.Add("Title").DataType = typeof(string);
            dt.Columns.Add("Value").DataType = typeof(int);

            DataRow firstRow = dt.NewRow();
            DataRow secndRow = dt.NewRow();
            DataRow thirdRow = dt.NewRow();

            firstRow[0] = "Invalid Mails";
            secndRow[0] = "Null Mails";
            thirdRow[0] = "Valid Mails";

            firstRow[1] = data.Where(Some Contition).Count();
            secndRow[1] = data.Where(Other Condition).Count();
            thirdRow[1] = data.Where(An Other Condition).Count();


            ViewBag.data = dt;

            return View();

As you all can see, I'm passing the DataTable filled with the willing Values as teh variable "data" in the ViewBag. Then, in the View, I fill the Javascript code using a foreach throught the datatable (ViewBag.data) i've passed, like this:

<script type="text/javascript">

    google.load('visualization', '1.0', { 'packages': ['corechart'] });

    function drawChart() {

        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
            @{int count = 0;}
            @foreach (DataRow row in ((DataTable)ViewBag.data).Rows)
                    if (count > 0)
                        @Html.Raw(",['" + row[0] + "'," + row[1] +"]");
                        @Html.Raw("['" + row[0] + "'," + row[1] +"]");

        var options = {
            'title': 'Title',
            'width': 400,
            'height': 300

        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);

Then, this visualization is trendered in the 'char_div' div that i have in my HTML:

    <div class="jumbotron">
        <br />
        <div class="row">
            <div id="chart_div"></div>

So... the question is: ┬┐There is a clean way to pass the total of 4 dataTables to the View And render 4 pieCharts respectively without having to repeat the JavaScript code 4 times?.

I guess that i've to loop inside the JavaScript 1 time for each dataTable I want to render, but i don't know how to tho it.

Thank you very much!

Related posts

Recent Viewed