1

I would like to set the colors in a google chart from my code, and not sure how to do it. I have this in a cshtml page.

<script type="text/javascript">

    // Load the Visualization API and the piechart package.
    //google.load('visualization', '1.0', { 'packages': ['bar'] });
    google.load('visualization', '1.0', { 'packages': ['corechart'] });
    var visualization;
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawCharts);

    function drawCharts() {

                var titleName = "Rounding Eligible";


                $("#chartHeader").html(titleName);
                var options = {
                    'backgroundColor': 'transparent',
                    title: titleName,
                    subtitle: 'Range of ddd to ddd', seriesType: "bars",isStacked: true,
                    series:  {  0:{color:"#009add"} ,1:{color:"#009844"} ,2: {color:"#ef7521"} ,3: {color:"#89d2e6"},4:{color:"#82bc00"},5:{color:"#f19f53"},6:{color:"#0055b7"},@(Model.NumSeries) : { type: "line", visibleInLegend: false, color: "#FF0000"  }},
                    vAxis:{title: "Count", minValue:10}

                };
                // Create the data table.
                var data = google.visualization.arrayToDataTable(@Html.Raw(Model.ChartJson));
                var chart_div = document.getElementById('chartDiv');
                var chart = new google.visualization.ComboChart(chart_div);

                chart.draw(data, options);

                //setup a temp image to gold hold the chart
                createHiddenImage('hiddenCanvas1', 'chartDiv', chart.getImageURI());
            }
    </script>

What I would like to do is replace my colors ( 0:{color:"#009add"} ,1:{color:"#009844"}) to be based on something in the code and do something like

 isStacked: true,
series: 
 @foreach seriesvalue in @Model.seriesValues
{@Html.Raw(seriesvalue);},  
Axis:{title: "Count", minValue:10}

I have no idea what is possible to accomplish this, is it best to just pass the whole options object from the model? Basically I can't figure out how to do it.

Brian Hanf
  • 544
  • 2
  • 11
  • 31

2 Answers2

1

Just use JSON serialization:

series: @Html.Raw(JsonConvert.SerializeObject(Model.seriesValues))

You'll want to make seriesValues a Dictionary keyed by the number you want associated with each color.

For a deeper dive, see this answer: Using Razor within JavaScript

Community
  • 1
  • 1
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • That comes close, but I get {"0":"{color:\"#009add\"}", in the text instead of {0:{color:"#009add"}, – Brian Hanf Oct 29 '15 at 15:26
  • 1
    @BrianHanf: Sorry, that's HTML escaping. You just need to add `Html.Raw()` around it. See my update. – StriplingWarrior Oct 29 '15 at 16:18
  • Funny I found that just a few minutes ago and finished testing I was about to come and add that note. I needed to also remove the extra " and replace the \" with ", i'll edit to show that change – Brian Hanf Oct 29 '15 at 16:42
  • @BrianHanf: Yeah, if you construct your `seriesValues` using an anonymous object rather than a string, it won't have that problem. Instead of `"{color:\"#009add\"}"`, you want `new {color = "#009add"}` – StriplingWarrior Oct 29 '15 at 16:48
  • @BrianHanf: I rejected your edit because that's not the right approach. You want your `seriesValues` objects to use object structures instead of strings in the first place. Then you won't need to remove quotes or anything. – StriplingWarrior Oct 29 '15 at 16:50
0

You can access properties from your model anywhere on the page, including within the script, via:

@Model.MyPropertyName

With that in mind, your javascript can look something like this:

myColor = '@Model.MyGreenColorProperty';

Note the single quotations around the @Model... this is very important, and will not work if the value is not surrounded by the quotes.

Kevin
  • 151
  • 3
  • 11
  • I am building an array or list of the colors for each column, not sure how a single color would help, am I missing a step? – Brian Hanf Oct 29 '15 at 15:28
  • While this might work for specific cases, it's not a good approach to use generally. If the value you output has an apostrophe, you'll break the entire script. If you use JSON Serialization instead, then a string value will automatically have quotes around it, and any quotes inside will be escaped appropriately. – StriplingWarrior Oct 29 '15 at 16:21