Hi rani,
Check this example. Now please take its reference and correct your code.
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("Year", typeof(string)),
new DataColumn("ToBill",typeof(decimal)),
new DataColumn("Billed",typeof(decimal))});
dt.Rows.Add(2011, 1000, 500);
dt.Rows.Add(2012, 2500, 100);
dt.Rows.Add(2013, 100, 50);
dt.Rows.Add(2014, 1000, 500);
dt.Rows.Add(2015, 400, 200);
dt.Rows.Add(2016, 3000, 2000);
dt.Rows.Add(2017, 2500, 100);
dt.Rows.Add(2018, 100, 50);
dt.Rows.Add(2019, 2500, 100);
dt.Rows.Add(2020, 100, 50);
ChartData chartData = new ChartData();
string[] Labels = (dt.AsEnumerable().Select(p => p.Field<string>("Year"))).Distinct().ToArray();
chartData.Labels = Labels;
List<string> datasetLabels = new List<string>();
for (int i = 1; i < dt.Columns.Count; i++)
{
datasetLabels.Add(dt.Columns[i].ColumnName);
}
chartData.DatasetLabels = datasetLabels.ToArray();
List<decimal[]> datasetDatas = new List<decimal[]>();
for (int i = 0; i < chartData.DatasetLabels.Length; i++)
{
List<decimal> data = new List<decimal>();
for (int j = 0; j < Labels.Length; j++)
{
decimal amount = (dt.AsEnumerable().Where(p => p.Field<string>("Year") == Labels[j])
.Select(p => p.Field<Decimal>(chartData.DatasetLabels[i]))).FirstOrDefault();
data.Add(amount);
}
datasetDatas.Add(data.ToArray());
}
chartData.DatasetDatas = datasetDatas;
ViewBag.Data = JsonConvert.SerializeObject(chartData);
return View();
}
public class ChartData
{
public string[] Labels { get; set; }
public string[] DatasetLabels { get; set; }
public List<decimal[]> DatasetDatas { get; set; }
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.4.0/dist/chartjs-plugin-datalabels.min.js"></script>
<script type="text/javascript">
$(function () {
var datas = '@ViewBag.Data'.replace(/"/g, '"')
var label = JSON.parse(datas).Labels;
var datasetLabels =JSON.parse(datas).DatasetLabels;
var datasetDatas =JSON.parse(datas).DatasetDatas;
var dataSets = [];
for (var i = 0; i < datasetDatas.length; i++) {
var dataSet = {
label: datasetLabels[i],
backgroundColor: GetRandomColor(),
borderColor: 'red',
borderWidth: 1,
data: datasetDatas[i]
};
dataSets.push(dataSet);
}
var ctx = document.getElementById("chart").getContext('2d');
new Chart(ctx, {
type: 'bar',
data: { labels: label, datasets: dataSets },
options: {
responsive: true,
title: { display: true, text: 'Year wise Amount' },
legend: { display: true, position: "top" },
layout: {
padding: { left: 50, right: 50, top: 50, bottom: 50 }
},
scales: {
xAxes: [{ stacked: true }],
yAxes: [{ stacked: true, ticks: { beginAtZero: true } }]
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var toBill = data['datasets'][0]['data'][tooltipItem['index']];
var billed = data['datasets'][1]['data'][tooltipItem['index']];
var percentage = Math.round(((billed / toBill) * 100), 2);
return percentage + '%';
}
}
},
plugins: {
datalabels: {
display: true,
align: 'center',
anchor: 'center',
color: "red"
},
display: function (ctx) {
return 1;
}
},
animation: {
onComplete: function () {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = "left";
ctx.font = "bold 15px Open Sans ";
ctx.textBaseline = 'bottom';
this.data.datasets[0].data.forEach(function (data, index) {
var total = data + this.data.datasets[1].data[index];
var meta = chartInstance.controller.getDatasetMeta(1);
var posX = meta.data[index]._model.x;
var posY = meta.data[index]._model.y;
if (total > 0) {
ctx.fillText(total, posX , posY);
ctx.fillStyle = "black";
}
}, this);
}
},
}
});
});
function GetRandomColor() {
var trans = '0.3';
var color = 'rgba(';
for (var i = 0; i < 3; i++) {
color += Math.floor(Math.random() * 255) + ',';
}
color += trans + ')';
return color;
}
</script>
</head>
<body>
<canvas id="chart" style="width: 800px; height: 400px;"></canvas>
</body>
</html>
Screenshot