Search code examples
javascriptc#asp.nethighchartsdotnethighcharts

Highcharts not referenced error when using setOptions


We are currently using the DotNet.Highcharts API to incorporate Highcharts into our website. However, we are having some JavaScript reference issues when using the .SetOptions(GlobalOptions) call.

We are using a wrapper class to build our chart in the controller, then using a simple view to render it.

In our controller:

Chart chart = new HighCharts("chart-id");
chart.SetOptions(new GlobalOptions { Global = new Global { UseUTC = false; } });
chart.SetPlotOptions()...

In our view:

@model HighchartWrapper

@(Model.Chart)

The chart is rendered in the view as follows:

<script type="text/javascript">
    Highcharts.setOptions({ global: { useUTC: false } });
    var chart05;
    $(document).ready(function() {
    });
</script>

Chrome is raising an

"Uncaught ReferenceError: Highcharts is not defined"

error on the .setOptions() statement. Without this (and the corresponding .SetOptions() statement in .NET) the chart renders correctly. If I navigate off this page and then back again, the charts start to render correctly.

I've found that manipulating the ToHtmlString() return value to put the .setOptions call to inside the .ready() portion makes the charts display properly. Is this the approach that others have had to resort to?


Solution

  • Your suspicions are right, you need to run your relevant code within doc ready as follows.

    $(document).ready(function() {
        var chart = new Highcharts.Chart(options);
    });
    

    According to the docs, the examples are all executed once the dom is loaded, so it's likely safe to assume this is best practice and expect that within the javascipt libraries, code that is executing will depend on the .ready function. Surely digging through the source will answer any further questions you have, but this is totally fine.

    Highcharts - How to set options