2

我尝试添加一些我想在 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% 确定。

4

3 回答 3

3

匿名类型在声明它的范围内是本地的。在类型声明的范围之外,您不会轻易地从它那里获取属性。 相关问题

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

var dummyData = new[]
        {
            Tuple.Create(1, 1, true, "Yes?", "int"),
        }.ToList();
        ViewBag.Header = dummyData;
于 2013-04-22T15:34:01.573 回答
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;

这应该够了吧。

于 2013-04-24T14:57:31.877 回答
1

foreach将您的定义更改为:

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

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

于 2013-04-22T15:24:53.480 回答