【问题标题】:How to bind MVC data to Plotly如何将 MVC 数据绑定到 Plotly
【发布时间】:2019-02-15 10:10:50
【问题描述】:

我正在尝试将 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 文件中,用于处理硬编码数据。

【问题讨论】:

  • x 中的 x += array.Data[i].Title; 是什么(您尚未在任何地方声明)。而xs 只是一个空数组,因此没有要显示的数据(无论如何,它需要是x: xs,而不是x: [xs]
  • 无论如何,如果您在 GET 方法中正确生成模型(通过为 x 和 y 值创建具有 2 个集合属性的模型并将其传递给视图),这将容易得多
  • 嗨,x 和 y 应该是 xs 和 ys,正如我在上面更新的那样。我认为我需要将所有数据发送到视图并在视图中对其进行操作,因为我希望稍后添加几个过滤器,我相信这在 JavaScript 中是最简单的。
  • 始终创建一个视图模型来表示您在视图中想要的内容(并且您当前的模型在没有 javascript 操作的情况下不会这样做!) - 但是如果您想使用您当前的代码,那么它的 @987654329 @
  • 也应该是array = @Html.Raw(Json.Encode(ViewBag.jsondata))

标签: javascript json asp.net-mvc plotly


【解决方案1】:

要将您的 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);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    相关资源
    最近更新 更多