Sunday, 31 May 2015

Chart.js with ASP.net MVC 5

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







3 comments:

  1. Very good. The only thing I am not sure about is the way the json data is accessed. For example data.Month may be undefined. No big deal. The idea is here...

    ReplyDelete
  2. Hi! I was following this tutorial of yours, But I'm getting an error. Can u help me out? Thanks!

    ReplyDelete
  3. Hello,

    I tried with this steps, but got this output: {"Month":["Jan","Feb","Mar"],"Expences":[100,200,300],"Income":[111,222,333]}

    Please help and let me know why this data? and not a chart is appearing on UI.

    ReplyDelete