Chartjs-Displaying Chart with data retrieved from Entity Framework in Controller

2๐Ÿ‘

โœ…

u never added it to the collection

see below

public ActionResult Timeline()
{
    var articleQuery = from a in artDb.dbArticle
                       select new { a.Date, a.StockPriceClose };

    List<DataPoint> dataPoints = new List<DataPoint>();


    foreach (var item in articleQuery)
    {
        double stockPriceClose = double.Parse(item.StockPriceClose.ToString());
        DateTime date = Convert.ToDateTime(item.Date);

        **
        var dataPoint =  new DataPoint(date, stockPriceClose);
        dataPoints.add(dataPoint )
        **
    }             

    ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
    return View();
}

1๐Ÿ‘

Your code is using the viewbag object as json object, but it is actually a string,
JsonConvert.SerializeObject return type is a string you can check the documentation and see Return Value Type: A JSON string representation of the object.

    ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);

this will be string, you need to parse that string to JSON object,
you can use JSON.parse() function to do this.

 dataPoints: JSON.parse('@Html.Raw(ViewBag.DataPoints)')

Leave a comment