1

I'm having some trouble passing an array from controller to a javascript in a view. I'm using ASP .Net MVC3 and i'm trying to make some charts/graphics with data from a database, i found HighCharts javascript and i'm trying to work with it.

Here's the example:

$(function () {
var chart;
$(document).ready(function() {
    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
        },
        title: {
            text: 'Browser market shares at a specific website, 2010'
        },
        tooltip: {
            formatter: function() {
                return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
            }
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    formatter: function() {
                        return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
                    }
                }
            }
        },
        series: [{
            type: 'pie',
            name: 'Browser share',
            data: [
                ['Firefox',   45.0],
                ['IE',       26.8],
                ['Chrome',       12.8],
                ['Safari',    8.5],
                ['Opera',     6.2],
                ['Others',   0.7]
            ]
        }]
    });
});

});

I made this class:

public class RegistoPie
{
    public string na { get; set; }
    public double da { get; set; }


    public RegistoPie(string n, double d) {

        na = n;
        da = d;

    }
}

and i send this object to the view trying to fill the data variable in the javascript:

var pie = new [] { new RegistoPie("papa",20.0), new RegistoPie("pepe",50.0) };

but its returning something like:

[{"na":"papa","da":20},{"na":"pepe","da":50}];

so its not the same syntax as data variable in javascript which only has:

[[string,double], [,] , ... ]

Help anyone?! Ty, Hélder

1 Answer 1

2

in controller:

ViewBag.Array = new[] { new RegistoPie("papa", 20.0), new RegistoPie("pepe", 50.0) };

in View:

@{
    var myArray = ViewBag.Array as TestMVC.Controllers.RegistoPie[];

    for (int i = 0; i < myArray.Length; i++)
    {
        var item = myArray[i];
    <text> ['@item.na', @item.da] @((myArray.Length - 1) != i ? "," : "")</text>
    }
}
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.