Hi nabilabolo,
Check this example. Now please take its reference and correct your code.
Database
CREATE TABLE Sampling
(
Id INT IDENTITY PRIMARY KEY,
inspection_type VARCHAR(50)
)
GO
INSERT INTO Sampling
SELECT 'B,C,E'
UNION
SELECT 'B,C,E,D'
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
TestEntities db = new TestEntities();
// Getting data from database and spliting comma separated into List.
List<string> inspections = new List<string>();
foreach (Sampling type in db.Samplings)
{
for (int i = 0; i < type.inspection_type.Split(',').Length; i++)
{
inspections.Add(type.inspection_type.Split(',')[i].ToString());
}
}
// Getting type and Count from List.
var result = inspections.GroupBy(x => x).Select(x => new { type = x.Key, count = x.Count() });
List<string> typeList = new List<string>();
List<int> typeCount = new List<int>();
foreach (var item in result)
{
typeList.Add(item.type);
typeCount.Add(item.count);
}
TempData["X"] = string.Join(",", typeList);
TempData["Y"] = string.Join(",", typeCount);
return View();
}
}
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 labels = '<%=TempData["X"] %>';
var datas = '<%=TempData["Y"] %>';
var labelsArray = new Array();
var dataArray = new Array();
for (var i = 0; i < labels.split(',').length; i++) {
labelsArray.push(labels.split(',')[i]);
dataArray.push(datas.split(',')[i]);
}
var ctx1 = document.getElementById("lineChart").getContext('2d');
var lineChart = new Chart(ctx1, {
type: 'bar',
data: {
labels: labelsArray,
datasets: [{
label: '% Overall Sampling by Platform',
backgroundColor: '#3EB9DC',
data: dataArray
}]
},
options: {
tooltips: { mode: 'index', intersect: false },
responsive: true,
scales: {
xAxes: [{ stacked: true}],
yAxes: [{ stacked: true}]
}
}
});
});
</script>
<canvas id="lineChart" height="150" width="200"></canvas>
Screenshot