使用匿名对象创建列表

时间:2013-04-22 15:23:37

标签: c# asp.net-mvc-3

我尝试添加一些虚拟记录,我想在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%肯定。

3 个答案:

答案 0 :(得分:3)

匿名类型是声明它的作用域的本地类型。在类型声明的范围之外,您无法轻易地从中获取属性。 Related question

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

var dummyData = new[]
        {
            Tuple.Create(1, 1, true, "Yes?", "int"),
        }.ToList();
        ViewBag.Header = dummyData;

答案 1 :(得分:2)

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;

这应该可以解决问题。

答案 2 :(得分:1)

将您的foreach定义更改为:

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

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

相关问题