Search code examples
c#asp.net-mvcasp.net-mvc-3mschart

Values in a pie chart


How do you display the values of each pie in a pie chart using ChartHelper? I am using MVC3/Razor syntax.

Trying to do something like this:

Pie

The image is from this tutorial for ChartHelper in MVC:

My code:

var bytes = new Chart(600, 300).AddSeries(
                    chartType: "pie",
                    legend: "Sales in Store per Payment Collected",
                    xValue: viewModel.SalesInStorePerPaymentCollected.XValues,
                    yValues: viewModel.SalesInStorePerPaymentCollected.YValues
                    )
                    .GetBytes("png");


            return File(bytes, "image/png");

Solution

  • I did it by using the System.Web.UI.DataVisualization.Charting.Chart class.

    Here is the code in my Controller:

    public ActionResult Chart()
    {
        Chart chart = new Chart();
        chart.ChartAreas.Add(new ChartArea());
    
        chart.Series.Add(new Series("Data"));
        chart.Series["Data"].ChartType = SeriesChartType.Pie;
        chart.Series["Data"]["PieLabelStyle"] = "Outside"; 
        chart.Series["Data"]["PieLineColor"] = "Black";
        chart.Series["Data"].Points.DataBindXY(
            data.Select(data => data.Name.ToString()).ToArray(), 
            data.Select(data => data.Count).ToArray());
        //Other chart formatting and data source omitted.
    
        MemoryStream ms = new MemoryStream();
        chart.SaveImage(ms, ChartImageFormat.Png);
        return File(ms.ToArray(), "image/png");
    }
    

    And the View:

    <img alt="alternateText" src="@Url.Action("Chart")" />