javascript - 如何将 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 文件中,用于处理硬编码数据。
解决方案
要将您的ViewBag
属性分配给 javascript 数组,请使用
var array = @Html.Raw(Json.Encode(ViewBag.jsondata))
然后在for
循环中,您需要.push()
将值放入您的xs
和ys
数组中
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);
};
推荐阅读
- ms-access - MS Access 查询在小窗口中打开,只有 8 行
- php - WooCommerce 在订单电子邮件中显示使用的优惠券
- r - 合并具有共同元素的行
- python - 我无法在 python 的数据框中删除特定值
- python - 如何检索会话名称?
- python - unittest:NameError:名称'dbutils'未定义
- java - Arquillian 和 Flyway 使用不同版本的 H2 内存
- laravel - Dompdf 上的问题,为尝试转换传递的无效字符,这些已被忽略
- php - 文件获取多个文件的内容和字符串替换
- c - 构造 C 代码的最佳方法,其中 malloc 在函数内部使用但在调用函数时自由