首页 > 解决方案 > 如何将 MVC 数据绑定到 Plotly

问题描述

我正在尝试将 JSON 数据绑定到 MVC 中的 Plotly 图。控制台为空,图表根本不显示。我对这样做的替代方法持开放态度。

我有一个 MVC 模型:

public class DataUploadModels
{
    [Key]
    public int id { get; set; }
    public string Empname { get; set; }
    public string Empid { get; set; }
    public string Title { get; set; }
    public decimal Annualizedbase { get; set; }
    public decimal Annualizedtcc { get; set; }
    public decimal grade { get; set; }
}

它有一些示例数据,我将这些数据返回到 JSON 中的视图:

public ActionResult Plotly()
{
    List<DataUploadModels> list = db.DataUploadModels.ToList();
    ViewBag.jsondata = this.Json(list);

    return View();
}

我试图在我看来创建一个简单的情节:

<div id="tester" style="width:600px;height:250px;"></div>
<script>
array = @Json.Encode(ViewBag.jsondata)
xs = [];
for (i = 1, i < 3, i++){
    xs += array.Data[i].Title;
};
ys = [];
for (i = 1, i < 3, i++){
    ys += array.Data[i].Annualizedbase;
};
TESTER = document.getElementById('tester');
Plotly.plot( TESTER, [{
x: xs,
y: ys }], {
margin: { t: 0 } } );
</script>

Plotly 包含在 _Layout.cshtml 文件中,用于处理硬编码数据。

标签: javascriptjsonasp.net-mvcplotly

解决方案


要将您的ViewBag属性分配给 javascript 数组,请使用

var array = @Html.Raw(Json.Encode(ViewBag.jsondata))

然后在for循环中,您需要.push()将值放入您的xsys数组中

var array = @Html.Raw(Json.Encode(ViewBag.jsondata))
xs = [];
for (i = 1, i < 3, i++){
    xs += array.push(Data[i].Title);
};
ys = [];
for (i = 1, i < 3, i++){
    ys += array.push(Data[i].Annualizedbase);
};

推荐阅读