ASP.NET MVC 3.0 Chart Helper display Legend

Vasya Pupkin picture Vasya Pupkin · May 17, 2011 · Viewed 9.3k times · Source

Is there any way to display legend on chart using chart helper?

It is not displaying it by default, there is no property i can say to display and if i specify legend in xml :

<Legends>
    <Legend _Template_=""All"" BackColor=""Black"" Docking=""Bottom"" Font=""Trebuchet MS, 8.25pt, style=Bold"" LegendStyle=""Row"" >
    </Legend>
  </Legends>  

It is also not working.

There is method in chart helper public Chart AddLegend(string title = null, string name = null); but when i am calling it i can't see not the legend on my chart, chart not displaying as well.

Chart chart = new System.Web.Helpers.Chart(width: 120, height: 300, theme: chartStyle: ChartTheme.Green.ToString()) 
                .AddLegend("title", "name") // not existed legends, that's why error.
                .AddSeries(
                    chartType: "Column"
                    legend: "Rainfall"
                    xValue: new[] { "jan", "feb", "mar", "apr", "may" },
                    yValues: new[] { "20", "20", "40", "10", "10" });

.Getting error: Series 'Series1' uses non-existing legend name 'Rainfall'. Set Legend property value to Default

If i change legend: "Rainfall" to legend: "Default" getting same error.

How could i make this legend name existed? For example in case of using System.Web.UI.DataVisualization.Charting directly it will be looking like that:

        chart.Legends.Add("Legend1");

        // show legend based on check box value
        chart.Legends["Legend1"].Enabled = true;

But how to achieve the same thing with helper?

Answer

Adam picture Adam · Jul 5, 2011

You need to give each Series a name, then call the AddLegend() with no parameters to add the Legend.

    var chart = new Chart(width: 600, height: 250)
        .AddSeries(
            chartType: "column",
            xValue: new [] { 2010, 2011, 2012 },
            yValues: new[] { 100, 125, 150 },
            name: "Forecasts")
        .AddSeries(
            chartType: "column",
            xValue: new[] { 2010, 2011, 2012 },
            yValues: new[] { 200, 225, 250 },
            name: "Actuals")
        .AddLegend();