To create pie chart in asp.net MVC using jquery HighChart.
step 1: Include latest jquery.min.js in your page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
step 2: Create a div which will contain the chart area
<div id="container" style="min-width: 250px; height: 205px; margin: 0 auto;"></div>
Step 3: Include highchart.js file at the end of the page.
<script type="text/javascript" src="@Url.Content("~/Scripts/js/highcharts.js")"></script>
step 4: Initialize highchart component.
<script type="text/javascript">
var chart;
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
colors: ['#FF1C97', '#FFF263', '#5090db', '#db843d', '#aa4643', '#3d96ae', '#80699b', '#89a54e', '#f2f437']
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: '#FFFFFF',
plotBorderWidth: null,
plotShadow: false,
backgroundColor: '#FFFFFF'
//margin: [0, 0, 0, 0]
},
legend: {
width: 180,
borderColor: '#FFFFFF',
floating: true,
align: 'left',
x: 0, // = marginLeft - default spacingLeft
y: 10,
itemWidth: 90,
enabled: false
},
title: {
text: '',
style: {
color: '#000000'
}
},
tooltip: {
valueDecimals: 2,
formatter: function () {
return this.point.name + this.percentage.toFixed(2) + ' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: GetNewSeries()
});
});
function GetNewSeries() {
$.ajax({
type: "POST",
url: '@Url.Content("~/<ControllerName>/<ActionName>/")',
success: function (av) {
chart.addSeries({
type: 'pie',
name: '',
data: av
});
}
});
}
step 5: Create controller and action where from you want to get data
public class ChartController : Controller
{
public JsonResult PieChart()
{
List<GetPieChartSeries> lstGetPieChartSeries = getdataFromBackend();
return Json(lstGetPieChartSeries, JsonRequestBehavior.AllowGet);
return Json("", JsonRequestBehavior.AllowGet);
}
}
step 6: In last add class to div.
<script type="text/javascript">
$("#container rect").addClass("pieChartColor");
</script>
Thank you and enjoy great coding experience.
0 Comment(s)