Hi nabilabolo,
Check this example. Now please take its reference and correct your code.
I have just changed the linq query for example. So you need to change the query as per your table structure.
I have set the default Date as 1997-10-13. Change the Date with current Date using DateTime.Now.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Controller
public class HomeController : Controller
{
NorthwindEntities db = new NorthwindEntities();
// GET: /Home/
public ActionResult Index()
{
DateTime date = Convert.ToDateTime("1997-10-13");
var result = from o in db.Orders
// Where condtiton to filter record based on Current Date.
where o.OrderDate == date.Date
select new
{
UserName = o.ShipCountry,
Type = o.OrderDate
};
GetJsonString(result);
return View();
}
[HttpPost]
public ActionResult Index(FormCollection fc)
{
DateTime fromDate = Convert.ToDateTime(fc["txtFrom"]);
DateTime toDate = Convert.ToDateTime(fc["txtTo"]);
var result = from o in db.Orders
// Where condtiton to filter record between Start Date and End Date.
where o.OrderDate >= fromDate.Date && o.OrderDate <= toDate.Date
select new
{
UserName = o.ShipCountry,
Type = o.OrderDate
};
GetJsonString(result);
return View();
}
private void GetJsonString(dynamic result)
{
List<UserType> inspections = new List<UserType>();
foreach (var item in result)
{
for (int i = 0; i < item.Type.ToString().Split(',').Length; i++)
{
inspections.Add(new UserType { UserName = item.UserName, Type = Convert.ToDateTime(item.Type.ToString().Split(',')[i]).ToString("yyyy") });
}
}
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);
}
}
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 Order by Country' },
tooltips: { mode: 'index', intersect: false, mode: 'label'
},
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>
<%using (Html.BeginForm()) {%>
<%:Html.TextBox("txtFrom") %>
<%:Html.TextBox("txtTo") %>
<input type="submit" value="Search" />
<%} %>
Screenshot