Hi rani,
Check this example. Now please take its reference and correct your code.
Controller
using System.Data;
using System.Linq;
public class HomeController : Controller
{
public IActionResult Index()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("Product", typeof(string)),
new DataColumn("Total", typeof(int))
});
dt.Rows.Add("Chair", 56);
dt.Rows.Add("Table", 69);
dt.Rows.Add("Stool", 5);
ViewBag.Product = string.Join(",", dt.AsEnumerable().Select(r => r.Field<string>("Product")).ToArray());
ViewBag.Total = string.Join(",", dt.AsEnumerable().Select(r => r.Field<int>("Total")).ToArray());
return View();
}
}
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/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function () {
var labels = '@ViewBag.Product';
var datas ='@ViewBag.Total';
var labelsArray = new Array();
var dataArray = new Array();
var colorArray = new Array();
for (var i = 0; i < labels.split(',').length; i++) {
labelsArray.push(labels.split(',')[i]);
dataArray.push(datas.split(',')[i]);
colorArray.push(getRandomColor());
}
new Chart(document.getElementById("chart").getContext('2d'), {
type: 'pie',
data: {
labels: labelsArray,
datasets: [{
backgroundColor: colorArray,
data: dataArray
}]
}
});
});
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</head>
<body>
<div class="box-body">
<div class="chart-container">
<canvas id="chart" style="width:100%; height:500px"></canvas>
</div>
</div>
</body>
</html>
Screenshot