ChartJS从Controller获取数据

时间:2015-03-05 13:51:00

标签: c# razor chart.js

我正在尝试使用ChartJS在我拥有的mvc 5项目中创建一个饼图。

我想将数据从我的控制器传递到我的视图,但图表永远不会被渲染

这是我的模特

public class ChartData {
    public int? value { get; set; }
    public string color { get; set; }
}

这是我的控制器

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();
    }
}

这是我的观点

@{
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>

知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

我有同样的问题,但我已经解决了。 请在此处查看完整的详细示例:

型号:

//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; }
    }

控制器:

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);
        }

查看:

@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>