MVC 5 (Razor) 在视图中使用莫里斯面积图显示数据库数据

MVC 5 (Razor) display database data in View using morris area chart

我创建了 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?
}

您查看模型需要 2 个属性 IEnumerable<string> LabelsIEnumerable<T> Data,其中 T 是包含 periodiphone 等属性的模型。例如

public 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; }
}

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

生成它
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);

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

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

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

视图模型还可以包含插件所需的其他属性,例如 List<string> LineColors