我尝试添加一些虚拟记录,我想在 ASP.NET MVC 3 View 中使用这些记录来为某些实验提供数据。我试试这个:
var dummyData = new[]
{
new {Row = 1, Col = 1, IsRequired = true, QuestionText = "Yes?", FieldValue = "int"},
new {Row = 1, Col = 2, IsRequired = true, QuestionText = "Yes?", FieldValue = "int"},
new {Row = 2, Col = 1, IsRequired = true, QuestionText = "No?", FieldValue = "string"},
new {Row = 3, Col = 1, IsRequired = false, QuestionText = "No?", FieldValue = "string"}
}.ToList();
ViewBag.Header = dummyData;
但是,当我尝试使用我的 View 中的数据时:
@{
foreach (var item in ViewBag.Header)
{
<tr><td>@item.QuestionText</td><td>@item.FieldValue</td></tr>
}
}
我收到此错误 - “object”不包含“QuestionText”的定义
。我认为我创建列表的方式有问题,但不能 100% 确定。
最佳答案
匿名类型对于声明它的范围而言是本地的。您将无法轻松地获取类型声明范围之外的属性。 Related question .
我建议使用 Tuple 或只为数据创建一个简单的 POCO 对象。
var dummyData = new[]
{
Tuple.Create(1, 1, true, "Yes?", "int"),
}.ToList();
ViewBag.Header = dummyData;
关于c# - 使用匿名对象创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16150767/