如何解决图表不显示在ASP.NET MVC页面上?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (50)

调节器:

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        List<string> iData = new List<string>();
        List<string> iData2 = new List<string>();

        iData.Add("Sam");
        iData2.Add("555");
        iData.Add("Alex");
        iData2.Add("666");
        iData.Add("Michael");
        iData2.Add("777");

        ViewBag.Value_List = iData2;
        ViewBag.Name_List = iData;

        return View();
    }
}

视图:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Charts</title>
    <script src="~/Scripts/Chart.min.js"></script>
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script>

        var barChartData =
            {
                labels: [@Html.Raw(ViewBag.Name_List)],
                datasets: [{
                    label: 'ChartTest',
                    backgroundColor: [
                        "#f990a7",
                        "#aad2ed",
                        "#9966FF",
                        "#99e5e5",
                        "#f7bd83",
                    ],
                    borderWidth: 2,
                    data: [@ViewBag.Value_List]
                }]
            };

            window.onload = function () {
                var ctx1 =     document.getElementById("barcanvas").getContext("2d");
                window.myBar = new Chart(ctx1,
                    {
                        type: 'bar',
                        data: barChartData,
                        options:
                            {
                                title:
                                {
                                    display: true,
                                    text: "ChartTest"
                                },
                                responsive: true,
                                maintainAspectRatio: true
                            }
                    });
            }
    </script>
</head>
<body>
    <div style="text-align: center">
        <canvas id="barcanvas"></canvas>
    </div>
</body>
</html> 
提问于
用户回答回答于

需要两个更改:

在控制器中将数据序列化为JSON:

using System.Web.Script.Serialization;

var js = new JavaScriptSerializer();
ViewBag.Value_List = js.Serialize( iData2);
ViewBag.Name_List = js.Serialize(iData);

删除视图中多余的方括号:

labels: @Html.Raw(ViewBag.Name_List),

data: @Html.Raw(ViewBag.Value_List)

你需要创建“放入”JavaScript代表数据:

labels: ["555","666","777"] ,

data: ["Sam","Alex","Michael"] 

扫码关注云+社区

领取腾讯云代金券