【问题标题】:Charts in ASP NET Core MVCASP NET Core MVC 中的图表
【发布时间】:2018-03-12 07:08:21
【问题描述】:

我想要结果页面上的图表。我有一堂课结果

    using System;

namespace PersonalArea.DAL.Models
{
    public class Result
    {
        public string Id { get; set; }

        public string PatientId { get; set; }

        public string GameName { get; set; }

        public string Time { get; set; }

        public int Score { get; set; }

        public int Level { get; set; }

        public DateTime FirstEnter { get; set; }

        public DateTime DateEnter { get; set; }

        public DateTime DateExit { get; set; }

        public string DifficultLevel { get; set; }

        public virtual Patient Patient { get; set; }
    }
}

在 PatientController 中有一些方法

[HttpGet]
    public async Task<IActionResult> Results(string id)
    {
        if (string.IsNullOrEmpty(id))
        {
            return NotFound();
        }
        Patient patient = await _userManager.FindByIdAsync(id) as Patient;
        if (patient == null)
        {
            return NotFound();
        }
        IQueryable<IGrouping<string, Result>> results = _context.Results.Where(x => x.PatientId == id).GroupBy(z => z.GameName);
        return View(results);
    }

在Results.cshtml中有一段代码:

@model IQueryable<IGrouping<string, PersonalArea.DAL.Models.Result>>
@inject IJsonHelper Json;

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    <title>Index</title>
</head>
<body>
    <div id="chartContainer"></div>

    <script type="text/javascript">
        var model = @Html.Raw(Json.Serialize(Model));
        var datapoints = [];
        // build an array of objects
        $.each(model, function(index, item) {
    datapoints.push({ x: new Date(item.DateEnd), y: item.scores });


		window.onload = function () {
			var chart = new CanvasJS.Chart("chartContainer", {
				theme: "theme2",
				animationEnabled: true,
				title: {
					text: "Simple Column Chart in ASP.NET MVC"
				},
				subtitles: [
					{ text: "Try Resizing the Browser" }
				],
				data: [
				{
                        type: "column", //change type to bar, line, area, pie, etc
                        dataPoints: datapoints
                    /*[
					{ x: 10, y: 71 },
					{ x: 20, y: 55 },
					{ x: 30, y: 50 },
					{ x: 40, y: 65 },
					{ x: 50, y: 95 },
					{ x: 60, y: 68 },
					{ x: 70, y: 28 },
					{ x: 80, y: 34 },
					{ x: 90, y: 14 }
					]*/
                                        //Uncomment below line to add data coming from the controller.
					//dataPoints: @Html.Raw(ViewBag.DataPoints),
				}
				]
			});
			chart.render();
		};
    </script>

</body>
</html>	

但是系统有错误:

处理请求时发生未处理的异常。

JsonSerializationException:检测到类型为“PersonalArea.DAL.Models.Result”的自引用循环。路径“[0][0].patient.results”。

请帮我解决这个错误

【问题讨论】:

标签: javascript asp.net asp.net-core


【解决方案1】:

您可以更改Newtonsoft.Json 配置以忽略自引用循环,如下所示:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
= Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

或者您只能在序列化调用中执行此操作:

JsonConvert.SerializeObject(objectToSerialize, Formatting.Indented, 
new JsonSerializerSettings { 
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

您有以下选择:

  • ReferenceLoopHandling.Error 这是默认设置,如果检测到引用循环将引发错误。这就是您得到异常的原因。
  • ReferenceLoopHandling.Serialize 在对象嵌套但 不是无限期的。
  • ReferenceLoopHandling.Ignore 不会序列化 对象,如果它是它自己的子对象。

【讨论】:

  • 我可以在哪里使用它?
  • 以上代码中发生的事情是,在您的 DAL 模型中,您有一个自引用循环,这意味着您的某些 Parient 属性是一个 Result 对象或类似的东西。当您在视图中序列化模型时,它会引发异常。在这段代码中,您应该使用我在上面编写的选项,这意味着您应该使用序列化选项传递另一个参数。
  • 另一件事,比将 DAL 对象发送到视图更好的方法是使用视图模型,其中只发送视图需要的信息。例如,您可以使用 AutoMapper 来完成转换两个模型对象的工作。
【解决方案2】:
[HttpGet]
    public async Task<IActionResult> Results(string id)
    {
        if (string.IsNullOrEmpty(id))
        {
            return NotFound();
        }
        Patient patient = await _userManager.FindByIdAsync(id) as Patient;
        if (patient == null)
        {
            return NotFound();
        }
        list<Result> query = _context.Results.Where(x => x.PatientId == id).GroupBy(z => z.GameName).ToList();
ViewBag.Test = JsonConvert.SerializeObject(query);
        return View(results);

中查看.chtml
 <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    <div id="chartContainer" style="height: 400px;"></div>

    <script type="text/javascript">
        window.onload = function ()
        {
            var test = @Html.Raw(ViewBag.test);
            var datapoints = [];

     for (var i = 0; i < test.length; i++) {
                datapoints.push({ y: test[i].Score, x: test[i].ID, label: test[i].GameName });
            }
window.onload = function () {
            var chart = new CanvasJS.Chart("chartContainer", {
                theme: "theme2",
                animationEnabled: true,
                title: {
                    text: "Simple Column Chart in ASP.NET MVC"
                },
                subtitles: [
                    { text: "Try Resizing the Browser" }
                ],
                data: [
                {
                        type: "column", //change type to bar, line, area, pie, etc
                        dataPoints: datapoints
                    /*[
                    { x: 10, y: 71 },
                    { x: 20, y: 55 },
                    { x: 30, y: 50 },
                    { x: 40, y: 65 },
                    { x: 50, y: 95 },
                    { x: 60, y: 68 },
                    { x: 70, y: 28 },
                    { x: 80, y: 34 },
                    { x: 90, y: 14 }
                    ]*/
                                        //Uncomment below line to add data coming from the controller.
                    //dataPoints: @Html.Raw(ViewBag.DataPoints),
                }
                ]
            });
            chart.render();
        };

        }

【讨论】:

  • 我尝试在 Contoller 中编写代码,如下所示 List query = _context.Results.Where(x => x.PatientId == id).GroupBy(z => z.GameName).ToList ();但出现错误“无法将类型从 System.Linq.IGrouping 转换为列表”。我能做什么?
  • 所以这个stackoverflow.com/a/49234780/9478131 告诉我新的问题,请告诉我,我该怎么办?
猜你喜欢
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
相关资源
最近更新 更多