Leron
Leron

Reputation: 9886

Create List with anonymous objects

What I try is add some dummy records which I want to use in an ASP.NET MVC 3 view to provide data for some experiments. I try this:

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;

However when I try to use the data in my view :

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

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

          }
       }

I get this error - 'object' does not contain a definition for 'QuestionText'. I'm thinking that there's something wrong with the way I create the list but not 100% sure.

Upvotes: 2

Views: 2940

Answers (3)

b_meyer
b_meyer

Reputation: 604

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;

That should do the trick.

Upvotes: 3

Jace Rhea
Jace Rhea

Reputation: 5018

An anonymous type is local to the scope from which it was declared. You are not going to easily be able to get properties off it outside the scope of the type declaration. Related question.

I would suggest using a Tuple or just create a simple POCO object for the data.

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

Upvotes: 3

Mike Perrenoud
Mike Perrenoud

Reputation: 67928

Change your foreach definition to this:

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

the problem is that they are anonymous classes so they need to be used as dynamic classes so the CLR can late bind the object at runtime.

Upvotes: 1

Related Questions