使用c#在控制器中创建数据结构并将其传递给视图

时间:2016-02-17 03:08:23

标签: javascript c# asp.net-mvc

我是asp.net MVC4的新手。我在我的asp.net mvc应用程序中使用了一些图表功能。

我搜索并找到了一个名为Chart.js的js库

http://www.chartjs.org/docs/#line-chart-data-structure 数据结构如下:

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        },
        {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }
    ]
};

我正在尝试从控制器中的数据库读取数据并将此数据传递到视图中,但始终无法显示图表。

我在控制器中试过这个:

int[] intArray = new int[7];
intArray[0] = 34;
intArray[1] = 1;
intArray[2] = 2;
intArray[3] = 23;
intArray[4] = 11;
intArray[5] = 11;
intArray[6] = 11;
ViewBag.proinfo = Json(intArray, JsonRequestBehavior.AllowGet).Data;

然后在视图中:

 {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(151,187,205,1)",
            ViewBag.proinfo
        }

但这对我不起作用。图表无法显示。

如何在c#controller中创建这个数据结构并将其传递给view?

非常感谢!

2 个答案:

答案 0 :(得分:0)

您可以在ViewBag.proinfo

中轻松指定值
ViewBag.proinfo = intArray;

您忘了在查看

中的json中定义数据
{
        label: "My Second dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data:ViewBag.proinfo
}

答案 1 :(得分:0)

试试这个:
在控制器中:

  

ViewBag.proinfo = intArray

在视图中

HTML
我假设你正在使用MVC Razor symtax​​