使用从Controller中的Entity Framework检索的数据显示图表

时间:2018-04-29 11:24:10

标签: c# asp.net-mvc entity-framework chart.js

我有一个包含新闻文章的数据库。我正在尝试制作一个图表,其中包含x轴上的日期和y轴上的股票价格,但数据点必须出错,因为它只显示带有标题/副标题的空白画布。

ArticleModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace SPScraper
{
    [Table("Article")]
    public class Article 
    {
        private string id;
        private string header;
        private string image;
        private string url;
        private string author;
        private string date;
        private string content;
        private decimal? stockPriceOpen;
        private decimal? stockPriceClose;

        public virtual string Id {
            get { return id; }
            set { id = value; }
        }
        public virtual string Header {
            get { return header; }
            set { header = value; }
        }
        public virtual string Image {
            get { return image; }
            set { image = value; }
        }
        public virtual string Url {
            get { return url; }
            set { url = value; }
        }


        public virtual string Author {
            get { return author; }
            set { author = value; }
        }
        public virtual string Date
        {
            get { return date;  }
            set { date = value; }
        }
        public virtual string Content
        {
            get { return content; }
            set { content = value; }
        }

        public virtual decimal? StockPriceOpen {
            get { return stockPriceOpen; }
            set { stockPriceOpen = value;  }
        }

        public virtual decimal? StockPriceClose
        {
            get { return stockPriceClose; }
            set { stockPriceClose = value; }
        }

    }
}

ArticlesController.cs

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

            new DataPoint(date, stockPriceClose);
        }             

        ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
        return View();
    }
    JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };

DataPointModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;

namespace SPScraperWeb.Models
{
    [DataContract]
    public class DataPoint
    {
        public DataPoint(DateTime x, double y)
        {
            this.X = x;
            this.Y = y;
        }

        //Explicitly setting the name to be used while serializing to JSON.
        [DataMember(Name = "x")]
        public Nullable<DateTime> X = null;

        //Explicitly setting the name to be used while serializing to JSON.
        [DataMember(Name = "y")]
        public Nullable<double> Y = null;
    }
}

Timeline.cshtml

    @model IEnumerable<SPScraper.Article>

@{
    ViewBag.Title = "Timeline";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

<h2>@Html.ActionLink("Articles", "Index") | @Html.ActionLink("Timeline", "Timeline")</h2>

<div id="chartContainer">

    <script type="text/javascript">

        window.onload =  $(function(result) {
            var chart = new CanvasJS.Chart("chartContainer", {
                theme: "light2",
                zoomEnabled: true,
                animationEnabled: true,
                title: {
                    text: "Facebook Stock Price by Article"
                },
                subtitles: [
                {
                    text: "Try Zooming and Panning"
                }
                ],
                data: [
                {
                    type: "line", 
                    dataPoints: @Html.Raw(ViewBag.DataPoints),
                }]
            });
            chart.render();
        });
    </script>
</div>

Blank Canvas

2 个答案:

答案 0 :(得分:2)

你从未将其添加到集合中

见下文

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 :(得分:1)

您的代码使用viewbag对象作为json对象,但它实际上是一个字符串, JsonConvert.SerializeObject返回类型是一个字符串,您可以查看文档并查看返回值类型:对象的JSON字符串表示。

    ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);

这将是字符串,您需要将该字符串解析为JSON对象, 您可以使用JSON.parse()函数执行此操作。

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