Chart helper in ASP.Net Display DateTime

2019-07-11 13:37发布

问题:

In a asp.net mvc application, I need to create a simple line-chart, so I tried Chart helper. The chart is created using two list, the x-axis should display datetimes, and the y-axis should display a value for each time. Now this works fine using the code below. "listOfDateTimes" consists a list of DateTimes.

    var chart = new Chart(width: 1000, height: 300, theme: ChartTheme.Green)
        .AddSeries(
                    chartType: "line",
                    xValue: listOfDateTimes,
                    yValues:  listOfValues )
                    .GetBytes("png");

The problem is that the datetimes below the x-axis shows up as "MM/dd/yyyy", but I also need to display the hour and minutes. I can't figure out how to solve this using Chart helper.

回答1:

When using Chart Helper you have to customize your chart by providing your own theme file:

 var myChart = new Chart(width: 800, height: 400, themePath: "MyTheme3.xml")
              .AddSeries(
                          chartType: "line",
                          xValue: new[] { DateTime.Now,
                              DateTime.Now.AddSeconds(1),
                              DateTime.Now.AddSeconds(2),
                              DateTime.Now.AddSeconds(3),
                              DateTime.Now.AddSeconds(4) },
                          yValues: new[] { 40, 100, 60, 80, 20 })

Use this sample theme to customize your X-axis as described:

MyTheme3.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Chart>
  <ChartAreas>
    <ChartArea Name="Default">
      <AxisX>
        <LabelStyle Format="MM/dd/yyyy hh:mm:ss"></LabelStyle>
      </AxisX>
    </ChartArea>
  </ChartAreas>
  <Series>
    <Series Name="Default"></Series>
  </Series>
</Chart>


EDIT: If you want to configure your chart the regular way through properties, then you should use System.Web.UI.DataVisualization.Charting namespace. But if you want to use System.Web.Helpers namespace then you have to do it like explained before.