有没有办法将从数据库查询到的动态JSON数据传递到图表格式(Google Charts API)?

von4xj4u  于 2022-12-27  发布在  Go
关注(0)|答案(1)|浏览(124)

我有一个ASP.NETCore3.1WebApp,它的功能是用户可以输入股票行情,然后使用查询检索数据来为他们创建图表(价格和日期)。我已经按照基本的谷歌图表API演练在我的应用程序中实现。如果数据是硬编码在JSON方法中,它的工作,但如果我想动态查看图表基于我输入的任何股票代码,图表没有接收到所需的JSON数据。
我所尝试的是有一个Ticker Entry页面(Action方法),它带有一个Form,该Form将用户输入的Ticker返回给Chart action方法。我想要的是Chart方法处理所有的LINQ查询,并将列表转换为JSONList,以便它可以传递给它的View方法。我将按顺序发布代码。
TickerEntry.cshtml

@using (Html.BeginForm("Chart", "Stocks", FormMethod.Get))
{
    <table>
        <tr>
            <td>Enter a Ticker to pull up its chart: </td>
            <td>@Html.TextBox("stockTicker")</td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Submit"></td>
        </tr>
    </table>
}

StocksController.cs

public List<StockLineChart> GetStockData(string stockTicker)
        {
            var list = new List<StockLineChart>();
            var result = (from s in _context.HistoricalDatas
                          where s.Ticker == stockTicker
                          select new { s.Price, s.DateOfClose });
            list = result.AsEnumerable()
                              .Select(sl => new StockLineChart
                              {
                                  Price = sl.Price,
                                  DateOfClose = Convert.ToDateTime(sl.DateOfClose)
                              }).ToList();

            return list;

           
        }

        public IActionResult TickerEntry()
        {            
            return View();
        }

 public IActionResult Chart(string stockTicker)
        {     
             //Returns the Chart View, but passes in the list of stock price&date transformed into JSON
            return View(GetLineChartJSON(GetStockData(stockTicker))); 
        }


public JsonResult GetLineChartJSON(List<StockLineChart> stockList)
        {   
            
            return Json(new { JSONList = stockList });
        }

Chart.cshtml

@{
    ViewData["Title"] = "Chart";
}

<div class="row">
    <div class="col-lg-12">
        <div id="chartdiv" style="width:1000px;height:350px;">
        </div>
    </div>
</div>

@section Scripts
{
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

        // Load the Visualization API and the corechart package.
        google.charts.load('current', { 'packages': ['corechart'] });

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(DrawChart);

        // Callback that creates and populates a data table,
        // instantiates the pie chart, passes in the data and
        // draws it.
        function DrawChart() {
            $(function () {
                $.ajax({
                    type: 'GET',
                    url: '/Stocks/GetLineChartJSON',
                    success: function (chartsdata) {
                        // Callback that creates and populates a data table,
                        // instantiates the pie chart, passes in the data and
                        // draws it.

                        //get jsonList from Object
                        var Data = chartsdata.jsonList;
                        var data = new google.visualization.DataTable();

                        
                        data.addColumn('string', 'DateOfClose');
                        data.addColumn('number', 'Price');

                        //Loop through each list data
                        for (var i = 0; i < Data.length; i++) {
                            data.addRow([Data[i].dateOfClose, Data[i].price]);
                        }

                        // Instantiate and draw our chart, passing in some options
                        var chart = new google.visualization.LineChart(document.getElementById('chartdiv'));

                        //Draw line chart command with data and chart options
                        chart.draw(data,
                            {
                                title: "Stock Chart",
                                position: "top",
                                fontsize: "14px",
                            });

                    },
                    error: function () {
                        alert("Error loading data! Please try again.");
                    }
                });
            })

        }
    </script>
}

我认为GetLineChartJSON不应该带任何参数,但很难做到这一点,因为它需要某种类型的数据(或者是查询列表的代码,或者是列表本身,以便转换为JSON)
例如,这将工作:
StockController.cs

public JsonResult GetLineChartJSON()
        {

            var list = new List<StockLineChart>();
            var result = (from s in _context.HistoricalDatas
                          where s.Ticker == "AC"
                          select new { s.Price, s.DateOfClose });
            list = result.AsEnumerable()
                              .Select(sl => new StockLineChart
                              {
                                  Price = sl.Price,
                                  DateOfClose = Convert.ToDateTime(sl.DateOfClose)
                              }).ToList();

       

            return Json(new { JSONList = list });
        }

注意,没有任何东西传入这个方法,stockTicker现在已经被硬编码为“AC”,这是我不希望的,因为用户可以选择他们想看的股票。
我希望我的解释没有把我的问题搞混,我愿意澄清任何误解。

dhxwm5r4

dhxwm5r41#

这里有一个完整的工作演示,你可以跟随:
Chart.cshtml

@{
    ViewData["Title"] = "Chart";
}
<div class="row">
    <div class="col-lg-12">
        <div id="chartdiv" style="width:1000px;height:350px;">
        </div>
    </div>
</div>

@section Scripts
    {
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

            google.charts.load('current', { 'packages': ['corechart'] });
            google.charts.setOnLoadCallback(DrawChart);

            function DrawChart() {
                $(function () {

                    var Data = @Html.Raw(ViewBag.StockTicker);  //get the ViewBag object

                    var data = new google.visualization.DataTable();
                    data.addColumn('string', 'DateOfClose');
                    data.addColumn('number', 'Price');

                    for (var i = 0; i < Data.length; i++) {
                        //change uppercase here....
                        data.addRow([Data[i].DateOfClose, Data[i].Price]); 
                    }

                    var chart = new google.visualization.LineChart(document.getElementById('chartdiv'));
                    chart.draw(data,
                    {
                        title: "Stock Chart",
                        position: "top",
                        fontsize: "14px",
                    });
                })
            }               
    </script>
}

主计长

public IActionResult TickerEntry()
{
    return View();
}
public List<StockLineChart> GetStockData(string stockTicker)
{
    var list = new List<StockLineChart>();
    var result = (from s in _context.HistoricalDatas
                    where s.Ticker == stockTicker
                    select new { s.Price, s.DateOfClose });
    list = result.AsEnumerable()
                        .Select(sl => new StockLineChart
                        {
                            Price = sl.Price,
                            DateOfClose = Convert.ToDateTime(sl.DateOfClose)
                        }).ToList();

    return list;
}

public IActionResult Chart(string stockTicker)
{
    //Use ViewBag instead....
    ViewBag.StockTicker =JsonConvert.SerializeObject(GetStockData(stockTicker));   
    return View();
}

//no need GetLineChartJSON method any more....

相关问题