How to implement chart js using viewbag in mvc razor - asp.net-mvc

I am using the following code in my MVC application on visual studio to generate a pie chart using the chartjs JavaScript framework. The text does get displayed in the console on the browser. But the chart is not visible.
The following error I get is undefined based on this property [#Html.Raw(ViewBag.ProductSalesCountName)]
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Pie Charts</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
<script>
var PieChartData =
{
labels: [#Html.Raw(ViewBag.ProductSalesCountName)],
datasets: [{
label: 'ProductWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [#ViewBag.ProductSalesCount]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("Piecanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'pie',
data: PieChartData,
options:
{
title:
{
display: true,
text: "ProductWise Sales Count"
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
</head>
<body>
<div style="text-align: center">
<canvas id="Piecanvas"></canvas>
</div>
<div style="text-align: center">
Disclaimer:- This data is for demo it is
not real data it wont relate to any company
</div>
</body>
</html>

This is because your serialization does not produce a valid javascript array.
First remove the square brackets from #Html.Raw(ViewBag.ProductSalesCountName)
And in the controller use Newtonsoft.Json for the serialization.
ViewBag.ProductSalesCountName=
Newtonsoft.Json.JsonConvert.SerializeObject(list);

Related

After using a selfdefined js function, Highcharts's select range in xAxis never stops in IE7, why?

My site want to use a function when xAxis.afterSetExtremes. But in IE7, when I am selecting a range in xAxis, the selecting cannot be stoped by the second click. Why?
This problem only happened in IE7.
The test page is: Here
The whole code is:
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/huidu.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="/js/html5shiv.min.js"></script>
<script src="/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
<div id="diantui" style="min-width:300px;height:400px">
</div>
</div>
</div>
<script>
function togglePlotbands() {
this.plotLinesAndBands.forEach(function(plotband) {
var ii = 1;
});
}
window.onload = function(){
var all_data = [];
all_data.push({x:1495641600000 , y: 1});
all_data.push({x:1497110300000 , y: 3});
all_data.push({x:1497210300000 , y: 4});
all_data.push({x:1497410300000 , y: 3});
all_data.push({x:1497510300000 , y: 2});
all_data.push({x:1497715300000 , y: 1});
all_data.push({x:1500134400000 , y: 2});
var hc_obj = {
chart: {
type: 'line',
zoomType: 'x',
renderTo: 'diantui',
events: {
load: function() {
togglePlotbands.call(this.xAxis[0]);
}
}
},
xAxis: {
plotBands: [
{color: '#FFFFEF',from: 1497110400000,to: 1497715200000,label: {text: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxfsdfsfsdfsfsdf'}}
],
events: {
afterSetExtremes: togglePlotbands
}
},
plotOptions: {
line: {
connectNulls: true,
marker: {
enabled: false
},
}
},
series: [
]
};
hc_obj['series'].push({name: 'xxx', data: all_data, visible: true});
var chart = new Highcharts.Chart(hc_obj);
}
</script>
</div>
<script src="//cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script>
<script src="http://cdn.hcharts.cn/highcharts/modules/exporting.js"></script>
<script src="/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>

how to draw charts with json file data in highcharts

my json.data file is in the same directory as my index.html file. data.json file looks like this:
{
data:
[
[1369540800000,20]
]
}
when I do:
alert(JSON.stringify(jsonData, null, 4));
I get this back, so I get the values. Still dont know what is wrong.
{
"data":[
[
1369540800000,
10
],
[
1369541700000,
20
]
]
}
my html file including java script to build the charts is below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>HIGHTCHARTS</title>
<style>
body
{
font: 10px arial;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$.getJSON('data.json', function(jsonData) {
chartOptions.series = jsonData;
chart = new Highcharts.Chart(chartOptions);
});
var chartOptions = {
chart: {
renderTo: 'container'
},
xAxis: {
type: 'datetime'
},
series: []
};
});
</script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
I see the chart title but I dont see any charts or data points. What am I missing here?
Your data is not in the right format. Familiarize yourself with how to format data for Highcharts.
These may help:
http://api.highcharts.com/highcharts#series.data
http://docs.highcharts.com/#preprocesssing-data-from-a-file
Notably:
1) your dates must be either a javascript time stamp (epoch time, in milliseconds), or a date.Utc declaration
2) your structure needs to be like:
[[date, value],[date,value],[date,value]]
this is what I had to do to make it work:
<script src="js/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'area'
},
xAxis: {
type: 'datetime'
},
series: [{}]
};
$.getJSON('dude.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>

string handle in rails makes difficulty

I have my google pie chart code
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
["Work", 50],
["Eat", 20],
["Commute", 20],
["Watch TV", 5],
["Sleep", 5]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I need to change it in ruby code.
here in #datas variable i have two field
#datas.each do |data|
data.name
data.value
It gives two value but i need to write in this order so that my code works like
['data.name, data.value]
How can i change my ruby code in google api formate? I did but i couldn't.
Try this:
#dates.map { |d| [d.name, d.value] }
EDIT: And the javascript code could be like this:
var data = google.visualization.arrayToDataTable(<%= #dates.map { |d| [d.name, d.value] }.inspect %>)

Hyperlinks in Dojo Tree

There is an example tree in the dojo campus with hyperlinks. They are not clickable. Does anyone have a dojo implementation with clickable links? Have you been able to determine which node/link was clicked? I am looking for sample code that does this.
Here is the sample code from dojo campus. How do I make these links clickable and how do I implement node selection from click of image?
Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr">
<head>
<style type="text/css">
body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.Tree");
var rawdata = [{
label: 'Something <b>important</b>',
id: '1',
children: [{
label: 'Life',
id: '1.1'
},
{
label: 'Liberty',
id: '1.2'
}]
},
{
label: 'Some links (note: the link is <b>not</b> clickable)',
id: '2',
children: [{
id: '2.1',
label: 'Dojo Toolkit'
},
{
id: '2.2',
label: '<img src="http://dojofoundation.org/media/img/dojo.logo.png" alt="greatest ever" height="32px" />'
},
{
id: '2.3',
label: 'my blog'
}]
}];
function prepare() {
var store = new dojo.data.ItemFileReadStore({
data: {
identifier: 'id',
label: 'label',
items: rawdata
}
});
var treeModel = new dijit.tree.ForestStoreModel({
store: store
});
var treeControl = new dijit.Tree({
model: treeModel,
showRoot: false,
_createTreeNode: function(
/*Object*/
args) {
var tnode = new dijit._TreeNode(args);
tnode.labelNode.innerHTML = args.label;
return tnode;
}
},
"treeOne");
}
dojo.addOnLoad(prepare);
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css"
/>
</head>
<body class=" claro ">
<div id="treeOne">
</div>
<!-- NOTE: the following script tag is not intended for usage in real
world!! it is part of the CodeGlass and you should just remove it when
you use the code -->
<script type="text/javascript">
dojo.addOnLoad(function() {
if (document.pub) {
document.pub();
}
});
</script>
</body>
</html>
You can do a connect to the onClick event on the Tree. When creating your Tree, add an extra onClick parameter to your constructor, pointing to a function with the following signature:
function myOnClickHandler(item, tree, evt){
//item is the node's DataStore item
//I forgot if tree is the whole tree or just the currtent node
//evt is the usual event object, with things like mouse position, etc...
console.log('clicked a tree');
}
var treeControl = new dijit.Tree({
model: treeModel,
showRoot: false,
_createTreeNode: function( /*Object*/ args) {
var tnode = new dijit._TreeNode(args);
tnode.labelNode.innerHTML = args.label;
return tnode;
},
onClick: myOnclickHandler // THIS LINE //
},
"treeOne");

JQuery mobile and highcharts integration

Has anyone managed to integrate highcharts with jquerymobile properly?
If i request a page containing some chart directly (i.e. http://mysite.com/mobile/page.html) the charts will initialize and render as expected. Instead, if i try to navigate to the same page using the anchor links, the page renders but the charts don't. I am using the "pageshow" event to initialize the charts.
Any feedback will be largely appreciated!
I had this same problem when I first started coding with jQuery Mobile... You have to bind your scripts on pagecreate, ie:
$(document).delegate("#page-id", "pagecreate", function() {
// highcharts, etc.
}
With jQuery mobile you need to put your page specific scripts and styles inside the page-content div. See "Known Limitations" in documentation.
I have tried what Tsar mentioned and for me it worked. What I did was:
Added the script within the head tag,
and added the div with the ID(rederTo) used in the script within the "page-content".
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Acura</title>
<link href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
<script src="libs/hightcharts/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart1; // globally available
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
});
</script>
</head>
<body>
<div id="ge" data-role="page">
<div data-role="header">
//header
</div>
<div data-role="content">
<div id="container"></div>
</div>
</div>
</body>
</html>

Resources