繁体   English   中英

使用匿名对象创建列表

[英]Create List with anonymous objects

我想做的是添加一些虚拟记录,这些记录要在ASP.NET MVC 3视图中使用,以提供一些实验数据。 我尝试这样:

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;

但是,当我尝试在视图中使用数据时:

@{
          foreach (var item in ViewBag.Header)
          {

              <tr><td>@item.QuestionText</td><td>@item.FieldValue</td></tr>

          }
       }

我收到此错误'object' does not contain a definition for 'QuestionText' 我认为我创建列表的方式出了问题,但不是100%肯定。

匿名类型在声明它的作用域中是本地的。 您将不容易在类型声明的范围之外获得属性。 相关问题

我建议使用元组或只为数据创建一个简单的POCO对象。

var dummyData = new[]
        {
            Tuple.Create(1, 1, true, "Yes?", "int"),
        }.ToList();
        ViewBag.Header = dummyData;
var dummyData = new List<dynamic>
        {
            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"}
        };
        ViewBag.Header = dummyData;

这应该够了吧。

将您的foreach定义更改为此:

@{ foreach (dynamic item in ViewBag.Header) {

问题在于它们是匿名类,因此需要将它们用作dynamic类,以便CLR可以在运行时后期绑定对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM