2016-07-16 90 views
1

我已经创建了MVC 5(使用Razor语法),其中我想使用morris-area-chart来显示数据。我想使用模型(即数据库)中的数据,我将其传入View中,以便可以在morris-area-chart中使用它。MVC 5(Razor)使用morris面积图在View中显示数据库数据

有人能告诉我如何构建并替换下面的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'], 

如果使用模型和剃刀语法是不可能实现我的上述请求,那么请演示显示从模型(即数据库)数据的正确方法。

检视:

@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? 
} 

回答

0

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

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

+0

您的解决方案非常完美,实施也非常简单。谢谢 :) – Lukasz

相关问题