im从控制器传递viewbag中的列表数据。当访问viewbag时,作为列表获取错误。
error - 'object' does not contain a definition for 'timeStamp'
查看
@model IEnumerable<TransformerEnergyMonitoring.Models.Total_Power>
<div class="row">
<div class="table-responsive">
<table id="myTable" class="table table-bordered table-hover table-striped">
<thead class="table-header">
<tr>
<th>Date</th>
<th>KWH Reading</th>
<th>KWH Consumption</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Total_PowerList)
{
<tr>
<td>@item.timeStamp</td>
</tr>
}
</tbody>
</table>
</div>
数据集
{ timeStamp = 12/5/2020 12:00:00 AM, finalState = 47326.95, consuption = 1455.71 }
当您使用viewbag时,它是一个动态结构,不关心内部的数据类型,您需要做的是将您的数据类型转换为您想要的类型这里是一个例子:
提供此TestModel
public class TestModel
{
public string Id { get; set; }
public int Number { get; set; }
public string Name { get; set; }
}
控制器中的此操作
public IActionResult Index()
{
var vm = new List<TestModel>() {
new TestModel(){
Id = "randomId1",
Name = "randomName1",
Number = 2
},
new TestModel(){
Id = "randomId2",
Name = "randomName2",
Number = 1
},
new TestModel(){
Id = "randomId3",
Name = "randomName3",
Number = 3
},
};
ViewBag.TestModels = vm;
return View();
}
在您的视图中,它应该类似于下面的@foreach(var item In(viewbag.testmodels as IEnumerable)){@item.id@item.number@item.name}
我假设在你的情况下,你想要铸造它的方式是
(ViewBag.Total_PowerList as IEnumerable<TransformerEnergyMonitoring.Models.Total_Power>)