我正在尝试将默认图表数据替换为 string 类型的 Model 元素形式的真实数据。任何人都可以演示完成此操作的正确语法吗?非常感谢。
使用默认数据显示的.datum脚本函数:
function cumulativeTestData() {
return [
{
key: "Closing Prices",
mean: 60,
values: [[1083297600000, 0.77078283705125], [1085976000000, 1.8356366650335], [1088568000000, 5.3121322073127], [1091246400000, 4.9320975829662], [1093924800000, 3.9835408823225], [1096516800000, 6.8694685316805], [1099195200000, 8.4854877428545], [1101790800000, 15.933627197384], [1104469200000, 15.920980069544], [1107147600000, 12.478685045651]]
},
];
}
我尝试过的示例:
values: @Model.ClosesJson //didn't work
values: <text> @Model.ClosesJson </text> //didn't work
values: $("#ClosesJson").val() //Model entity as hidden - didn't work
Controller 和模型字符串实体克隆默认数据Unix语法:
public ActionResult Dashboard()
{
ProjectEntities projectDb = new ProjectEntities();
var model = new DashboardViewModel();
model.Closes = new List<ClosesModel>();
var prices = projectDb.uspGetCloses().ToList();
foreach (var result in prices)
{
var close = new ClosesModel
{
Close = result.Close,
CloseCreatedDate = result.CloseCreatedDate
};
model.Closes.Add(close);
}
model.ClosesJson = "[[" + System.Convert.ToString(model.Closes[0]. CloseCreatedDate.Subtract(new DateTime(1970,1,1)).TotalMilliseconds) + ", " +
System.Convert.ToString(model.Closes[0]. Close) + "]";
for (int i = 1; i < model.Closes.Count; i ++)
{
model.ClosesJson = model.ClosesJson + ", [" + System.Convert.ToString(model.Closes[i].CloseCreatedDate.Subtract(new DateTime(1970,1,1)).TotalMilliseconds) +
", " + System.Convert.ToString(model.Closes[i].Close) + "]";
}
model.ClosesJson = model.ClosesJson + "]";
return View(model);
}
最佳答案
您当前只是传递一个字符串,而不是可以表示为 JSON 的对象。
因为您需要传递一个包含 2 个值的数组(代表图表 x 和 y 值),所以您需要创建一个匿名对象
并在您的主模型中添加一个属性
public object Coordinates { get; set; }
然后在 Controller 中
model.Coordinates = new[]
{
new []{1083297600000, 0.77078283705125F},
new []{1085976000000, 1.8356366650335F}
};
然后在你的脚本中
var values = JSON.parse('@Html.Raw(Json.Encode(Model.Coordinates))');
要从模型构建所需的数组格式,您可以使用
DateTime baseDate = new DateTime(1970, 1, 1);
object[] array = new object[prices.Count];
for(int i = 0; i < prices.Count; i++)
{
array[i] = new[]
{
prices[i].CloseCreatedDate.Subtract(baseDate).TotalMilliseconds,
prices[i].Close
};
}
model.Coordinates = array;
关于javascript - 在 JavaScript 中将模型数据传递到 nvd3 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32321065/