Reputation: 57
I am trying to create a Pie chart with the ChartJS in an mvc 5 project I have.
I want to pass the data from my controller to my view but the chart never gets rendered
Here is my model
public class ChartData {
public int? value { get; set; }
public string color { get; set; }
}
Here is my controller
public class HomeController : Controller {
// Declare Variables
DBEntities db = new DBEntities();//
// GET: /Home/
public ActionResult Index() {
DateTime today = DateTime.Now;
DateTime yesterday = today.AddDays(-1);
List<Get_IdentitiesByFaction_Sp_Result> model = db.Get_IdentitiesByFaction_Sp(0, 0, yesterday, today).Take(5).ToList();
List<ChartData> chartData = new List<ChartData>();
foreach (var item in model) {
chartData.Add(new ChartData() { value = item.Count, color = "#fff" });
}
ViewBag.ChartData = chartData;
return View();
}
}
And here is my view
@{
var data = ViewBag.ChartData;
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = js.Serialize(data);
}
<body>
<!-- pie chart canvas element -->
<canvas id="PieChart" width="600" height="400"></canvas>
<script>
// pie chart data
var pieData = '@json';
// pie chart options
var pieOptions = {
segmentShowStroke: false,
animateScale: true
}
// get pie chart canvas
var countries = document.getElementById("PieChart").getContext("2d");
// draw pie chart
new Chart(countries).Pie(pieData, pieOptions);
</script>
</body>
Any idea what I am doing wrong?
Upvotes: 1
Views: 5008
Reputation: 1757
I have same issue, but I have already fix it. Please see full detailed example here:
Model:
//for Pass data to Chart
public class Dataset
{
public Dataset()
{
data = new List<int>();
}
public string label { get; set; }
public string fillColor { get; set; }
public string strokeColor { get; set; }
public string pointColor { get; set; }
public List<int> data { get; set; }
}
public class RootObject
{
public RootObject()
{
labels = new List<string>();
datasets = new List<Dataset>();
}
public List<string> labels { get; set; }
public List<Dataset> datasets { get; set; }
}
Controller:
public ActionResult Chart()
{
//Get data from DB, items is list of objects:
//1. DisplayText - (string) - chart columns names (equals "labels")
//2. Value - (int) - chart values (equals "data")
var items = _Layer.GetData().ToList();
//check if data exists
if (items.Any())
{
string color = "#3c8dbc";
Dataset ds = new Dataset
{
label = string.Empty,
fillColor = color,
pointColor = color,
strokeColor = color
};
var data = items.Select(x => x.Value).ToList();
ds.data.AddRange(data);
model.datasets.Add(ds);
var labels = items.Select(x => x.DisplayText).ToList();
model.labels = labels;
}
var json = JsonConvert.SerializeObject(model, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
return PartialView("_Chart", json);
}
View:
@model String
<!-- ChartJS 1.0.1 -->
<script src="~/Assets/plugins/chartjs/Chart.min.js" type="text/javascript"></script>
<!-- BAR CHART -->
<div class="chart">
<canvas id="barChart" height="230"></canvas>
</div>
<script>
//-------------
//- BAR CHART -
//-------------
var barChartCanvas = $("#barChart").get(0).getContext("2d");
var barChart = new Chart(barChartCanvas);
//pass chart to Data from Controller
var barChartData = JSON.parse(@Html.Raw(Json.Encode(Model)));
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke: true,
//Number - Pixel width of the bar stroke
barStrokeWidth: 2,
//Number - Spacing between each of the X value sets
barValueSpacing: 5,
//Number - Spacing between data sets within X values
barDatasetSpacing: 1,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
//Boolean - whether to make the chart responsive
responsive: true,
maintainAspectRatio: false
};
barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions);
</script>
Upvotes: 1