如何在 ViewData 中动态显示来自控制器的数据作为集合 Highcharts

How to display data coming from the controller as collection in a ViewData dynamically Highcharts

控制器中的数据是从 SQL 数据库正确收集的,它确实存在于视图 Cshtml 的 viewData 中。

///型号

    public class ChartViewModel
{
    public int Year { get; set; }
    public int WeekNumber { get; set; }
    public int NumberOfCases { get; set; }
    public int Size { get; set; }

    public ChartViewModel(int year, int weeknr, int number, int size)
    {
        Year = year;
        WeekNumber = weeknr;
        NumberOfCases = number;
        Size = size;
    }
}

public class ChartViewModelsList
{
    public List<ChartViewModel> List { get; set; }

    public ChartViewModelsList()
    {
        List = new List<ChartViewModel>();
    }
}

///控制器

        public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";


        //fill the data for the chart
        //create a new, empty list
        Models.CaseMetricsList model = new Models.CaseMetricsList();

        //load the csv file into the model (list)
        SqlConnection sqlConn = new SqlConnection(GetConnectionString());
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter("select top(25) DATEPART(year, InsertedDateTime) as yearnr, DATEPART(week, InsertedDateTime) as weeknr,  count(*) as numberofcases,  sum(sourcecasesize) as Size from tblcases where CaseStatusId <> 4 group by DATEPART(year, InsertedDateTime), DATEPART(week, InsertedDateTime) order by DATEPART(year, InsertedDateTime), DATEPART(week, InsertedDateTime) asc ", sqlConn))
        {
            // create the DataSet 
            DataSet dataSet = new DataSet();
            // fill the DataSet using our DataAdapter 
            dataAdapter.Fill(dataSet);
            DataTable table = dataSet.Tables[0];
           
            foreach (DataRow dr in table.Rows)
            {
                model.List.Add(new Models.CaseMetricsModel(Convert.ToInt32(dr["Yearnr"]),
                                                     Convert.ToInt32(dr["weeknr"].ToString()),
                                                     Convert.ToInt32(dr["numberofcases"]),
                                                     Convert.ToInt32(dr["Size"])));
            }


            ViewData["usaData"] = model;

        }

        return View();

    }

///查看

   <script>
Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'New cases in Relativity per week'
    },
    xAxis: {
        type: 'category',
        categories: [
            @foreach(var item in @ViewData["usaData"] as IEnumerable<ChartViewModel>)
            {
                @item.List.Select(x => x.WeekNumber)
            }
        ],
        labels: {
            rotation: -45,
            style: {
                fontSize: '13px',
                fontFamily: 'Verdana, sans-serif'
            }
        }
    },
    yAxis: {
        min: 0,
        title: {
            text: '# cases'
        }
    },
    legend: {
        enabled: false
    },
    tooltip: {
        pointFormat: 'Number of new cases per week.'
    },
    series: [{
        name: 'Year/week',
        color: '#009286',
        data: @foreach(var item in @ViewData["usaData"] as IEnumerable<ChartViewModel>)
               {
                @item.List.Select(x => x.NumberOfCases)
               }
        dataLabels: {
            enabled: true,
            rotation: -90,
            color: '#FFFFFF',
            align: 'right',
            format: '{point.y:.1f}', // one decimal
            y: 10, // 10 pixels down from the top
            style: {
                fontSize: '13px',
                fontFamily: 'Verdana, sans-serif'
            }
        }
    }]
});
</script>

但图表未显示,@foreach 返回异常。 应该如何显示视图中的数据(使用 viewData 或 ViewBag)才能正确显示图形? 谢谢。

我认为你应该分配

ViewData["usaData"] = model.List;

并且在视图中

@foreach(var item in @ViewData["usaData"] as IEnumerable<CaseMetricsModel>)