passing data series to highcharts Jquery from C# code

Am building a  column highchart with the rotated labels similar to this
http://www.highcharts.com/demo/column-rotated-labels/grid

I have difficulty passing an array to the data series . I have tried various formats ,but nothing works. Please help!.

C#
 I have a variable called userorders, it is a dictionary<strint,int> t ype

Am loading that variable from the database

  UserOrders.AddOrUpdate(userName, orderCount, (s, i) => orderCount);

Then am loading the values to a List<string> with the format needed for the Data series

 UserCountByRep.Add(string.Format("['{0}',{1}]", userName, orderCount));

This will format it to  ['user1',2],['user2',3]....  similar to  the one mentioned in the Highcharts code examples.
 ['Shanghai', 23.7],
                ['Lagos', 16.1],
                ['Instanbul', 14.2],
                ['Karachi', 14.0],
                ['Mumbai', 12.5],
                ['Moscow', 12.1],
                ['São Paulo', 11.8],
                ['Beijing', 11.7],
                ['Guangzhou', 11.1],
                ['Delhi', 11.1],
                ['Shenzhen', 10.5],
                ['Seoul', 10.4],
                ['Jakarta', 10.0],
                ['Kinshasa', 9.3],
                ['Tianjin', 9.3],
                ['Tokyo', 9.0],
                ['Cairo', 8.9],
                ['Dhaka', 8.9],
                ['Mexico City', 8.9],
                ['Lima', 8.9]

Then i pass the UserCountByRep  variable to the Chart Data series .  But it is not working .
gladstonesheebaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Najam UddinCommented:
Problem might be is with  the JSON structure you are sending ( may be missing "{ and "}")

[code]var jsonResult = Json(yourList);
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
return jsonResult;

Open in new window


OR

string DictionaryToJson(Dictionary<string, int> dict)
{
    var entries = dict.Select(d =>
        string.Format("\"{0}\": [{1}]", d.Key, d.Value);
    return "{" + string.Join(",", entries) + "}";
}

Open in new window

0
Julian HansenCommented:
How are you consuming this in your script?

Is your script AJAX'ing the data after page load or are you embedding the data as JavaScript into the page?

If the latter (JSON is not applicable) the chart expects an array of arrays so you would want to emit something like this
<script>
var chartdata = [
  ['Shanghai', 23.7],
  ['Lagos', 16.1],
  ['Instanbul', 14.2],
  ['Karachi', 14.0],
  ['Mumbai', 12.5],
  ['Moscow', 12.1],
  ['São Paulo', 11.8],
  ['Beijing', 11.7],
  ['Guangzhou', 11.1],
  ['Delhi', 11.1],
  ['Shenzhen', 10.5],
  ['Seoul', 10.4],
  ['Jakarta', 10.0],
  ['Kinshasa', 9.3],
  ['Tianjin', 9.3],
  ['Tokyo', 9.0],
  ['Cairo', 8.9],
  ['Dhaka', 8.9],
  ['Mexico City', 8.9],
  ['Lima', 8.9]
]
</script>

Open in new window

Note the enclosing [ ] around the list of items.
You then use the chartdata variable as your series
$('#container').highcharts({
  ...
  series: [{
    name: 'Population',
    data: chartdata,
    ...

Open in new window

0
gladstonesheebaAuthor Commented:
I tried both Julian's and Nadam's solution. But still not working.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Julian HansenCommented:
But still not working.
You need to give us more than that.
Were there errors?
Did you check the console for errors?
What does the rendered page look like?

Do a view source and copy the HTML and paste here so we can see what is actually being rendered.

Try to give us something to work with.
0
gladstonesheebaAuthor Commented:
Hi,
  Please find the attached document  with my source codes in it . Thanks for your help!. I appreciate it  .
0
gladstonesheebaAuthor Commented:
If i pass the values with the same format as [['user1,0],...] then am getting the chart as shown in the attached picture .
chartCode.docx
orders.jpg
0
Julian HansenCommented:
@gladstonesheeba,
Please rather use the code tags for posting code - reading out of an attached doc is not a great way to work with code

This is where you are outputing your data
var chartdata=@Model.UserCounts;

Open in new window


What we need to see - is how that looks in the browser.

Please can you do the following
1. Open the page in your browser
2. Right click the page - you will see a context menu appear
3. One of the options in this menu is View Source - click that
4. This will open a new window showing the underlying HTML for your page.
5. Select ALL the HTML on this page and copy it to the clipboard
6. Paste the code here using the code tags

To use code tags
1. Click the CODE option in the toolbar of the post window
2. This will insert the following tags into the post window [code ] [/code ]
3. Put your cursor between the opening and closing tags and paste the code copied above

If we can see the underlying HTML we can see where the output is not being created correctly.
0
gladstonesheebaAuthor Commented:
Please see the below "ViewSource" code .

<!DOCTYPE html>
<html>
<head>
    <title></title>
 
    <script src="https://code.highcharts.com/highcharts.js" type="text/javascript"></script>
<script src="https://code.highcharts.com/modules/exporting.js" type="text/javascript"></script>
</head>

<body>
    

<script type="text/javascript">

    $(document).ready(function () {

      var chartdata=[[&#39;R. Hayes&#39;,2],[&#39;U. Test&#39;,0],[&#39;L. Bennett&#39;,1],[&#39;A. Quijada&#39;,0],[&#39;S. Ballard&#39;,0],[&#39;J. Giles&#39;,1]];
         setDailyOrdersbyRep(chartdata);
        
    });

    
</script>


          

             <div id="RepOrders">
                  <div id="OrdersbyRep" ></div>
                 
            </div>
	</div>





<script src="/Assets/Scripts/salessupport.js" type="text/javascript"></script>





</body>
</html>

Open in new window

0
gladstonesheebaAuthor Commented:
Could anyone help me on solving this issue please ?. I posted the code as well , but no response yet?.
0
Julian HansenCommented:
Apologies I did not see your earlier post.

Let's look at this step by step.

1. You have an extra closing </div> in your source - you might want to look at that
2. Lets look at your data. There is lots wrong with it.
Compare this
var chartdata=[[&#39;R. Hayes&#39;,2],[&#39;U. Test&#39;,0],[&#39;L. Bennett&#39;,1],[&#39;A. Quijada&#39;,0],[&#39;S. Ballard&#39;,0],[&#39;J. Giles&#39;,1]];

Open in new window

To this
<script>
var chartdata = [
  ['Shanghai', 23.7],
  ['Lagos', 16.1],
  ['Instanbul', 14.2],
  ['Karachi', 14.0],
  ['Mumbai', 12.5],
  ['Moscow', 12.1],
  ['São Paulo', 11.8],
  ['Beijing', 11.7],
  ['Guangzhou', 11.1],
  ['Delhi', 11.1],
  ['Shenzhen', 10.5],
  ['Seoul', 10.4],
  ['Jakarta', 10.0],
  ['Kinshasa', 9.3],
  ['Tianjin', 9.3],
  ['Tokyo', 9.0],
  ['Cairo', 8.9],
  ['Dhaka', 8.9],
  ['Mexico City', 8.9],
  ['Lima', 8.9]
]
</script>

Open in new window

In your data your strings are not enclosed in quotes - Javascript is going to error on that array as it is invalid. You need to fix your output so that it encloses your strings in quotes.

I can't tell if there are other errors because I am missing some of your code - you would need to also post where
a) setDailyOrdersbyRep is defined
b) Where you are creating and rendering your chart.
I am assuming both are in the salesupport.js script

Steps going forward
1. Fix your markup - remove the orphan </div>
2. Fix your output to enclose your strings in quotes
3. Post your salesupport.js script so I can test all your code.
0
gladstonesheebaAuthor Commented:
&#39; is nothing but a single quotes. It is showing as an HTML code .  Am not sure how to output it to show it in strings as am already doing those steps in the C# code

  var chartData = sortedDict.Select(d => string.Format("['{0}',{1}]", d.Key, d.Value));
 var  Userorder Counts = "[" + string.Join(",", chartData) + "]";

Below is my JS code.

var repOrdercounts;

function setDailyOrdersbyRep(chartData) {
   


    repOrdercounts = chartData;

    createOrderbyRepDailyChart();
}



function createOrderbyRepDailyChart() {

   
    repOrdersChart = new Highcharts.Chart({
        chart: {
            renderTo: 'OrdersbyRep',
            type: 'column'
        },
        title: {
            text: 'Daily Orders By Rep'
        },
        subtitle: { text: month_names[new Date().getMonth()] + " " + (new Date().getDate()),
            y: 45,
            style: { fontWeight: 'bold', fontSize: '1.5em' }

        },

        xAxis: {
            type: 'category',
            labels: {
                rotation: -45,

                style: {

                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }

        },
        yAxis: {
            min: 0,
            labels: {
                style: {
                    color: '#6e6e70'
                }
            },
            title: {
                text: 'Orders'
            }
        },

        navigator: {
            xAxis: {
                gridLineColor: '#D0D0D8'
            }
        },
        legend: {
            enabled: false
        },


      
        series: [{
            name: "Daily Order by Rep",
           
                       

data: repOrdercounts,
         
            color: 'green',
            dataLabels: {
                enabled: true,
                rotation: -90,
                color: '#FFFFFF',
                align: 'right',
                format: '{point.y:.1f}', // one decimal

                y: 10, // 10 pixels down from the top
                style: {
                    fontSize: '15px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }
        }]

    });
}

Open in new window

0
Julian HansenCommented:
I got your code with three changes

1. Changing the &#39 to single quote
2. Creating the month_names array - which was missing from the code you gave me.
3. Adding the jquery library to the code

Important to include JQuery before your Highchart scripts.

Here is the complete code
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery.js"></script>
 <script src="https://code.highcharts.com/highcharts.js" type="text/javascript"></script>
<script src="https://code.highcharts.com/modules/exporting.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
	var chartdata=[['R. Hayes',2],['U. Test',0],['L. Bennett',1],['A. Quijada',0],['S. Ballard',0],['J. Giles',1]];
    setDailyOrdersbyRep(chartdata);
});
</script>
<div id="RepOrders">
	<div id="OrdersbyRep" ></div>
</div>
</div>
<script src="js/salessupport.js" type="text/javascript"></script>
</body>
</html>

Open in new window

salessupport.js
var repOrdercounts;
var month_names = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

function setDailyOrdersbyRep(chartData) {
  repOrdercounts = chartData;
  createOrderbyRepDailyChart();
}

function createOrderbyRepDailyChart() 
{
  repOrdersChart = new Highcharts.Chart({
    chart: {
      renderTo: 'OrdersbyRep',
      type: 'column'
    },
    title: {
      text: 'Daily Orders By Rep'
    },
    subtitle: { 
      text: month_names[new Date().getMonth()] + " " + (new Date().getDate()),
      y: 45,
      style: { fontWeight: 'bold', fontSize: '1.5em' }
    },
    xAxis: {
      type: 'category',
      labels: {
        rotation: -45,
        style: {
          fontSize: '13px',
          fontFamily: 'Verdana, sans-serif'
        }
      }
    },
    yAxis: {
      min: 0,
      labels: {
        style: {
          color: '#6e6e70'
        }
      },
      title: {
        text: 'Orders'
      }
    },

    navigator: {
      xAxis: {
        gridLineColor: '#D0D0D8'
      }
    },
    legend: {
      enabled: false
    },
    series: [{
      name: "Daily Order by Rep",
      data: repOrdercounts,
      color: 'green',
      dataLabels: {
        enabled: true,
        rotation: -90,
        color: '#FFFFFF',
        align: 'right',
        format: '{point.y:.1f}', // one decimal
        y: 10, // 10 pixels down from the top
        style: {
          fontSize: '15px',
          fontFamily: 'Verdana, sans-serif'
        }
      }
    }]
  });
}

Open in new window

2 and 3 you can fix easily.

In terms of item 1 did you try the suggestions by Najam uddin from his post here (http://www.experts-exchange.com/questions/28794179/passing-data-series-to-highcharts-Jquery-from-C-code.html#a41152284)
0
gladstonesheebaAuthor Commented:
Thank you !. For Step 1, i have already tried  Najam uddin's code . Moreover, That's how am formatting the list to the one i want . i couldn't think of any other way to do .  but when you see in the viewsource once the page is loaded, i still see the &#39; attached to each instead of the quotes.
0
Julian HansenCommented:
Have you  tried to list the code as JSON?
0
gladstonesheebaAuthor Commented:
yes.
0
Julian HansenCommented:
... and what was the resulting output from that?

Remember you had 3 things wrong with your code anyone of which was a showstopper.
If you have fixed the other 2 you probably need to go back and test all the other mechanisms you tried for outputing your Dictionary - one of them was probably correct but failed because of the other issues on your page.

Can you post resulting HTML back here of the attempts you made with this.
0
gladstonesheebaAuthor Commented:
 <!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="/Assets/Stylesheets/Reset.css" rel="stylesheet" type="text/css" />
    <link href="/Assets/Stylesheets/Layout.css" rel="stylesheet" type="text/css" />
    <link href="/Assets/Stylesheets/Site.css" rel="stylesheet" type="text/css" />
    <link href="/Assets/Stylesheets/jquery.jqplot.min.css" rel="stylesheet" type="text/css" />
    <script src="/Assets/Scripts/lib/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Assets/Scripts/lib/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
    <script src="/Assets/Scripts/lib/jquery.mousewheel.min.js" type="text/javascript"></script>
    <script src="/Assets/Scripts/lib/jquery.kinetic.js" type="text/javascript"></script>
    <script src="/Assets/Scripts/lib/jquery.smoothdivscroll-1.3-min.js" type="text/javascript"></script>
  
    <script src="/Assets/Scripts/lib/date.js" type="text/javascript"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>

<body>
    

<script type="text/javascript">

    $(document).ready(function () {
  
  
      var chartdata= [[&#39;R. Hayes&#39;,0],[&#39;U. Test&#39;,0],[&#39;L. Bennett&#39;,0],[&#39;A. Quijada&#39;,0],[&#39;S. Ballard&#39;,0],[&#39;J. Giles&#39;,0]];
         setDailyOrdersbyRep(chartdata);
        
    });

    
</script>



	

       
      

             <div id="RepOrders">
                  <div id="OrdersbyRep" ></div>
                 
           </div>


<script src="/Assets/Scripts/salessupport.js" type="text/javascript"></script>





</body>
</html>

Open in new window

0
Julian HansenCommented:
What was the source that you used to create the last post?
0
Julian HansenCommented:
I got this to work doing the following - assuming MVC4

Controller
...
            string output = "";
            foreach (KeyValuePair<string, double> k in chartData){

                output += "['" + k.Key + "'," + k.Value + "],";
            }
            output = output.TrimEnd(',');
            ViewBag.chartData = output;

...

Open in new window

View
<script>
   var chartData = [@Html.Raw(ViewBag.chartData)];
</script>

Open in new window


Result
...
<script>
   var chartData = [['Lagos',16.1],['Instanbul',14.2],['Karachi',14],];
</script>
...

Open in new window

You need to force output of Raw string into your view.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.