Display Pie Chart in Chart.js Using MVC C# SQL Database
View Page:-
@{
ViewBag.Title = "DisplayPieChart";
}
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="~/Scripts/ChartJs/charts/Chart.min.js"></script>
<script src="~/Scripts/ChartJs/Legendtext/legend.legacy.js"></script>
<script>
$(document).ready(function () {
DispPieCharts();
});
function DispPieCharts() {
$.ajax({
url: "/chartjs/DispRec",
dataType: "text",
crossDomain: true,
success: function (data) {
var json = $.parseJSON(data);
var len = json.length;
var PieData = []
for (var i = 0; i < len; i++) {
PieData.push({
value: parseFloat(json[i].Percentage),
color: getRandomColor(),
label: json[i].Name + " ( " + parseInt(json[i].TotalCount) + " )" + "- (" + parseFloat(json[i].Percentage) + " % )"
});
}
console.log(PieData);
var ctx = document.getElementById("ChartjsPie").getContext("2d");
var chart = new Chart(ctx).Pie(PieData);
legend(document.getElementById("DivChartjsPie"), PieData, chart);
}
});
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</head>
<body>
<canvas id="ChartjsPie" width="250" height="250"></canvas>
<div id="DivChartjsPie"></div>
</body>
</html>
Controller:-
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Chartsprojects.Controllers
{
public class chartjsController : Controller
{
public ActionResult DisplayPieChart()
{
return View();
}
public class Det
{
public int Id;
public String Name;
public int TotalCount;
public decimal Percentage;
}
public JsonResult DispRec()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["blogger"].ToString());
List<Det> obj = new List<Det>();
cn.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter("select * from mCalc", cn);
da.Fill(dt);
cn.Close();
foreach (DataRow dr in dt.Rows)
{
Det def = new Det();
def.Id = Convert.ToInt32(dr[0].ToString());
def.Name = Convert.ToString(dr[1].ToString());
def.TotalCount = Convert.ToInt32(dr[2].ToString());
def.Percentage = Convert.ToDecimal(dr[3].ToString());
obj.Add(def);
}
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
}
Comments
Post a Comment
Thank You for your Comment