Charts asp.net MVC5

本文关键字:MVC5 net asp Charts | 更新日期: 2023-09-27 18:15:00

我想实现一个图表视图从数据库获取值

代码:

 @{
var db = Database.Open("aspnet-NewApp-20150923010220");
var data = db.Query("SELECT Name, Price FROM Product");
var myChart = new Chart(width: 600, height: 400)
    .AddTitle("Product Sales")
    .DataBindTable(dataSource: data, xField: "Name")
    .Write();
}

但是当我尝试使用database.opendb.query时,它说我无法解析符号,我该如何解决这个问题?

Charts asp.net MVC5

如果需要快速创建图表,请使用ChartHelper

将控制器动作的数据作为model传递给View

例如:

 public class Product
 {
    public string Name { get; set; }
    public string Price { get; set; }
 }
    [HttpGet]
    public ActionResult DrawChart()
    {
        var products = new List<Product>();
        string connectionString = @"Data Source=.;Initial Catalog=TestDb;Integrated Security=True";
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            using (SqlCommand command = new SqlCommand("SELECT Name, Price FROM Product", con))
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                   products.Add(new Product{ Name = reader.GetString(0), Price = reader.GetString(1)});
                }
            }
        }
        return View(products);
    }

根据需要自定义上述内容。(当然还有其他获取数据的方法)

View:

@model IEnumerable<Product>
@{
var myChart = new Chart(width: 500, height: 300, theme: ChartTheme.Green)
    .AddTitle("Product Sales")
    .AddSeries("Default",
               xValue: Model, xField: "Name",
               yValues: Model, yFields: "Price")
    .Write("png");
}

要对图表进行更多控制,请使用:System.Windows.Forms.DataVisualization.Charting