Home > Back-end >  Populate HighCharts Dataset in Javascript from ViewData Object .Net Core
Populate HighCharts Dataset in Javascript from ViewData Object .Net Core

Time:05-10

I'm trying to use HighCharts in .Net and having difficulty in populating the dataset that HighChart uses on the chart. Originally I was doing it in the view using the following:

new BubbleSeries
{
     Data = (ViewData["bubble1"] as List<BubbleSeriesData>)
},

This works, but it leaves me with having to do the rest of the formatting of HighCharts in the Razor view. HighCharts does not have a lot of extensive examples of formatting the different chart objects in .Net, relying more to utilizing javascript.
I thought I would try a different tact and build the chart in a script tag in the view. The issue I am having is how would I assign the "ViewData" to the data object.

How can I replace this:

series: [{
            data: [
                { x: 95, y: 95, z: 13.8, name: 'BE', country: 'Belgium' },
                { x: 86.5, y: 102.9, z: 14.7, name: 'DE', country: 'Germany' },
                { x: 80.8, y: 91.5, z: 15.8, name: 'FI', country: 'Finland' },
                { x: 80.4, y: 102.5, z: 12, name: 'NL', country: 'Netherlands' },
                { x: 80.3, y: 86.1, z: 11.8, name: 'SE', country: 'Sweden' },
                { x: 78.4, y: 70.1, z: 16.6, name: 'ES', country: 'Spain' },
                { x: 74.2, y: 68.5, z: 14.5, name: 'FR', country: 'France' },
                { x: 73.5, y: 83.1, z: 10, name: 'NO', country: 'Norway' },
                { x: 71, y: 93.2, z: 24.7, name: 'UK', country: 'United Kingdom' },
                { x: 69.2, y: 57.6, z: 10.4, name: 'IT', country: 'Italy' },
                { x: 68.6, y: 20, z: 16, name: 'RU', country: 'Russia' },
                { x: 65.5, y: 126.4, z: 35.3, name: 'US', country: 'United States' },
                { x: 65.4, y: 50.8, z: 28.5, name: 'HU', country: 'Hungary' },
                { x: 63.4, y: 51.8, z: 15.4, name: 'PT', country: 'Portugal' },
                { x: 64, y: 82.9, z: 31.3, name: 'NZ', country: 'New Zealand' }
            ]
        }]

with this:

series: [{
            data: [
               (ViewData["bubble1"] as List<BubbleSeriesData>)
            ]
        }]

CodePudding user response:

Here is a working sample:

model:

public class BubbleSeriesData {
        public int x { get; set; }
        public int y { get; set; }
        public int z { get; set; }
        public string name { get; set; }
        public string country { get; set; }

    }

ViewData:

List<BubbleSeriesData> ll = new List<BubbleSeriesData> { new BubbleSeriesData { x = 1, y = 1, z = 1, name = "n1", country = "c1" }, new BubbleSeriesData { x = 2, y = 2, z = 2, name = "n2", country = "c2" } };
    ViewData["bubble1"] = JsonConvert.SerializeObject(ll);

series:

series: [{
                data:@Html.Raw(JsonConvert.DeserializeObject(ViewData["bubble1"].ToString()))
            }],
  • Related