bobbyK12 bobbyK12 - 19 days ago 8
C# Question

How to add values to the top of column in MVC5 Chart?

I've created a basic .net MVC 5 app and am using System.Web.Helpers to generate a Column Chart based off of the information on www.asp.net HERE.

On of the examples on the page shows a label at the top of the column with the actual value for the field.(sorry, tried to upload picture but I've not got a high enough rep to embed images).

The code below generates the chart just fine in the browser, however, I can't seem to find a way to add the actual value at the top of the bar as show in the example.

the X and Y axis values are being populated by the LINQ query.

The results I've generated give me what we need, except for the actual value above the column...

Is it even possible using this method of creating a chart? If so, what am I missing?

View

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<div>
<img src="@Url.Action("ChartColumn")" alt="theChart" />

</div>


Controller:

public ActionResult ChartColumn()
{
var xValue = new ArrayList();
var yValue = new ArrayList();

var results = _context.SurveyResponses.DistinctBy(m => m.Q1).ToList();
results.ToList().ForEach(rs => xValue.Add(rs.Q1));
results.ToList().ForEach(rs => yValue.Add(rs.Q1.Length));


new System.Web.Helpers.Chart(width: 800, height: 400, theme: ChartTheme.Blue)
.AddTitle("Answers")
.AddSeries(chartType: "Column", xValue: xValue, yValues: yValue)
.Write("png");



return null;
}

Answer

In order to do that you have to provide your own custom chart theme. In particular, make IsValueShownAsLabel="true", like in the following sample:

 var myChart = new Chart(width: 600, height: 400, themePath: "MyTheme2.xml")
            .AddTitle("Product Chart")
            .AddSeries(
            name: "Products",
            xValue: data, xField: "productname",
            yValues: data, yFields: "quantity")
            .Save("~/Images/Chart01.png", "png");

MyTheme2.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Chart>
  <ChartAreas>
    <ChartArea Name="Default">
      <AxisX>
        <MajorGrid Enabled="false"></MajorGrid>
      </AxisX>
    </ChartArea>
  </ChartAreas>
  <Series>
    <Series Name="Products" IsValueShownAsLabel="true"></Series>
  </Series>
</Chart>

enter image description here