简体   繁体   中英

Charts asp.net MVC5

I want to implement a chart on view getting values from database

Code:

 @{
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();
}

But when I try to use database.open and db.query it says me cannot resolve symbol, how can I resolve this?

If you require quick chart creation, use the ChartHelper

Pass the data from your controller action as your model to the View .

Something like:

 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);
    }

Customize the above as required. (there are alternate ways to get the data ofcourse)

This is an example 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");
}

For more control over your chart use: System.Windows.Forms.DataVisualization.Charting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM