将数据从控制器传递到视图以构建绘图

Fra*_*oso 1 json asp.net-mvc-4 morris.js

我有点新的网络应用程序和javascript,jquery,json,淘汰赛等等的世界我试图做一些真正简单但没有开始工作.我想将数据从控制器传递到视图以使用morris.js构建绘图.

我谷歌它并尝试了几次尝试,没有成功.

视图收到类似这样的内容来构建图形:

<script>
    new Morris.Line({
    // ID of the element in which to draw the chart.
    element: 'myfirstchart',
    // Chart data records -- each entry in this array corresponds to a point on
    // the chart.
    data: [
    { year: '2008', value: 20 },
    { year: '2009', value: 10 },
    { year: '2010', value: 5 },
    { year: '2011', value: 5 },
    { year: '2012', value: 20 }
    ],
    // The name of the data record attribute that contains x-values.
    xkey: 'year',
    // A list of names of data record attributes that contain y-values.
    ykeys: ['value'],
    // Labels for the ykeys -- will be displayed when you hover over the
    // chart.
    labels: ['Value']
});
</script>
Run Code Online (Sandbox Code Playgroud)

现在我想使用viewbag或其他东西从控制器发送数据.对于我所理解的JSON是最正确的方法,只是不知道如何使用它.

你能告诉我怎么样吗?

von*_* v. 5

您可以拥有一个代表您的数据的viewmodel,然后在您的控制器中构建它的集合.然后,您可以通过ajax调用它并将其作为json对象返回.

ViewModel

public class YearlyStat {
    public int Year {get;set;}
    public int Value {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

在控制器中构建数据,如下所示:

public ActionResult Statistics() {
    // most probably the values will come from a database
    // this is just a sample to show you 
    // that you can return an IEnumerable object
    // and it will be serialized properly
    var stats = new List<YearlyStat> {
        new YearlyStat { Year=2008, Value=20},
        new YearlyStat { Year=2009, Value=10},
    }
    return Json(stats,JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

然后像这样消耗它:

$.get('@Url.Action("Statistics")', function(result){
    new Morris.Line({
        data: result,
    });
});
Run Code Online (Sandbox Code Playgroud)