MVC 5(Razor)使用morris区域图

时间:2016-07-16 09:46:30

标签: razor asp.net-mvc-5 morris.js

我创建了MVC 5(使用Razor语法),我希望使用morris-area-chart显示数据。我想使用模型中的数据(即数据库),我将其传递到我的视图中,以便我可以在morris-area-chart中使用它。

有人可以告诉我如何构建和替换以下morris-area-chart配置元素数据,以便使用从模型中获取的数据来设置这些元素吗?

data: [{ period: '2010-01-01', iphone: 2666, ipad: null, itouch: 2647 },
          { period: '2010-01-02', iphone: 2778, ipad: 2294, itouch: 2441 },
          { period: '2010-01-03', iphone: 4912, ipad: 1969, itouch: 2501 },
          { period: '2010-01-04', iphone: 3767, ipad: 3597, itouch: 5689 }], 
labels: ['iPhone', 'iPad', 'iPod Touch'],

如果使用模型和Razor语法无法实现上述请求,请说明从模型(即数据库)显示数据的正确方法。

查看:

@model Project.Models.ShowGraphViewModel
....
<div id="morris-area-chart"></div>

@section Styles {
    @Styles.Render("~/plugins/morrisStyles")
}

@section Scripts {
    @Scripts.Render("~/plugins/morris")

<script>
    Morris.Area({
    element: 'morris-area-chart',
    data: [{ period: '2010-01-01', iphone: 2666, ipad: null, itouch: 2647 },
           { period: '2010-01-02', iphone: 2778, ipad: 2294, itouch: 2441 },
           { period: '2010-01-03', iphone: 4912, ipad: 1969, itouch: 2501 },
           { period: '2010-01-04', iphone: 3767, ipad: 3597, itouch: 5689 }],
    xkey: 'period',
    ykeys: ['iphone', 'ipad', 'itouch'],
    labels: ['iPhone', 'iPad', 'iPod Touch'],
    xLabels: "day",
    pointSize: 2,
    hideHover: 'auto',
    resize: true,
    lineColors: ['#87d6c6', '#54cdb4', '#1ab394'],
    lineWidth: 2,
    pointSize: 1,
    });
</script>
}

控制器:

// GET: ShowGraph
public ActionResult ShowGraph()
{
    // Create model to pass to View
    ShowGraphViewModel graphModel = new ShowGraphViewModel();

    // How to construct following for morris-area-chart?
    // data: ?.....
    // labels = ?....

    return View(graphModel);
}

型号:

public class ShowGraphViewModel
{
    //What do I put in here?
}

1 个答案:

答案 0 :(得分:0)

您查看模型需要2个属性IEnumerable<T> DataT,其中period是包含iphonepublic class ChartDataVM { public string period { get; set; } public int iphone { get; set; } public int? ipad { get; set; } public int itouch{ get; set; } } public class ShowGraphViewModel { public IEnumerable<ChartDataVM> Data { get; set; } public IEnumerable>string> Labels { get; set; } } 等属性的模型。例如

var model = new ShowGraphViewModel()
{
     Data = new List<ChartDataVM>
     {
         new ChartDataVM(){ period  "2010-01-01", iphone = 2666, itouch = 2647 },
         new ChartDataVM(){ period  "2010-01-02", .... },
         ....
     },
     Labels = new List<string>(){ "iPhone", "iPad", .... }
};
return View(model);

并且在GET方法中,您可以使用

生成它
<script>
    var model = @Html.Raw(Json.Encode(Model))

    Morris.Area({
        element: 'morris-area-chart',
        data: model.Data,
        xkey: 'period',
        ....
        labels: model.Labels,
        ....

然后在视图中,您可以将模型分配给javascript对象并将其属性分配给插件

List<string> LineColors

视图模型还可以包含插件所需的其他属性,例如{{1}}