Hi nabilabolo,
Check this example. Now please take its reference and correct your code.
Namespaces
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Script.Serialization;
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
TestEntities db = new TestEntities();
// Getting data from database and spliting comma separated into List.
var result = from u in db.Userlists
join t in db.tasks on u.userid equals t.userid into ps
from t in ps.DefaultIfEmpty()
select new { UserName = u.username, Type = t.inspection_type != null ? t.inspection_type : "" };
List<UserType> inspections = new List<UserType>();
foreach (var item in result)
{
for (int i = 0; i < item.Type.Split(',').Length; i++)
{
inspections.Add(new UserType { UserName = item.UserName, Type = item.Type.Split(',')[i] });
}
}
DataTable dt = new DataTable();
dt.Columns.Add("UserName");
dt.Columns.Add("Type");
dt.Columns.Add("Count");
var results = inspections.GroupBy(x => new { x.UserName, x.Type }).Select(x => new { type = x.Key, count = x.Count() });
foreach (var item in results)
{
dt.Rows.Add(item.type.UserName, item.type.Type, item.count);
}
string[] users = (dt.AsEnumerable().Select(p => p["UserName"].ToString())).Distinct().ToArray();
string[] types = (dt.AsEnumerable().Where(x => x["Type"].ToString() != "")
.Select(p => p["Type"].ToString())).Distinct().OrderBy(x => x).ToArray();
List<decimal[]> datas = new List<decimal[]>();
for (int i = 0; i < types.Length; i++)
{
List<decimal> counts = new List<decimal>();
for (int j = 0; j < users.Length; j++)
{
counts.Add(dt.AsEnumerable()
.Where(p => p["UserName"].ToString() == users[j] && p["Type"].ToString() == types[i])
.Select(p => Convert.ToDecimal(p["Count"])).FirstOrDefault());
}
datas.Add(counts.ToArray());
}
ChartData chartData = new ChartData();
chartData.Labels = users;
chartData.DatasetLabels = types;
chartData.DatasetDatas = datas;
JavaScriptSerializer se = new JavaScriptSerializer();
TempData["Data"] = se.Serialize(chartData);
return View();
}
}
public class ChartData
{
public string[] Labels { get; set; }
public string[] DatasetLabels { get; set; }
public List<decimal[]> DatasetDatas { get; set; }
}
public class UserType
{
public string UserName { get; set; }
public string Type { get; set; }
}
View
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script type="text/javascript">
$(function () {
var json = JSON.parse('<%=TempData["Data"] %>');
var datasetDatas = json.DatasetDatas;
var dataSets = [];
for (var i = 0; i < json.DatasetLabels.length; i++) {
var dataSet = {
label: json.DatasetLabels[i],
backgroundColor: GetRandomColor(),
data: datasetDatas[i]
};
dataSets.push(dataSet);
}
var ctx1 = document.getElementById("lineChart").getContext('2d');
var lineChart = new Chart(ctx1, {
type: 'bar',
data: { labels: json.Labels, datasets: dataSets },
options: {
title: { display: true, text: 'Overall Inspection Type by User' },
tooltips: { mode: 'index', intersect: false },
legend: { display: true, position: "right" },
responsive: true,
scales: {
xAxes: [{ stacked: true}],
yAxes: [{ stacked: true}]
}
}
});
});
function GetRandomColor() {
var trans = '0.5';
var color = 'rgba(';
for (var i = 0; i < 3; i++) {
color += Math.floor(Math.random() * 255) + ',';
}
color += trans + ')';
return color;
}
</script>
<canvas id="lineChart" height="150" width="200"></canvas>
Screenshot