Here I have add some dummy
data in database for daily transactions details
Add Method in your Controller
to get data from Database and pass it to view in JSON formate
public JsonResult GetData()
{
DataTable dtTable = new DataTable();
List<string> lstMonth = new List<string>();
List<string> lstExpences = new List<string>();
List<string> lstIncome = new List<string>();
string strQuery = "sp_GetBarChartData";
SqlConnection con = new SqlConnection
(ConfigurationManager.ConnectionStrings["eXpenceMgrContext"].ToString());
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("TYPE", "Expences");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTable);
foreach (DataRow row in dtTable.Rows)
{
if (row["TransactionType"].ToString() == "Expences")
{
lstExpences.Add(row["Amount"].ToString());
}
lstMonth.Add(row["Month"].ToString());
}
cmd.Parameters.RemoveAt(0);
dtTable.Clear();
cmd.Parameters.AddWithValue("TYPE", "Income");
da.Fill(dtTable);
foreach (DataRow row in dtTable.Rows)
{
if (row["TransactionType"].ToString() == "Income")
{
lstIncome.Add(row["Amount"].ToString());
}
}
var BarChart = new
{
Month = lstMonth,
Expences = lstExpences,
Income = lstIncome,
};
return Json(BarChart, JsonRequestBehavior.AllowGet);
}
Now Create View and copy given code in <script></script>
And provide json data to the
Chart.js Method
function BarChart(data) {
var barChartData = {
labels: data.Month,
datasets: [
{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: data.Expences
},
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: data.Income
}
]
}
var ctx = document.getElementById("dvbarchart").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData,
{
responsive: true
});
}
Finally to bind the Chart in view you need to add canvas
tag in your View
<div style="width:550px;">
<canvas id="dvbarchart"></canvas>
</div>
and here is the final
output