1

Can some tell me why this ViewBag does not want to render its values?

ViewBag.fields = from f in db.Fields
                    where f.FieldId == id
                    select new { name = f.Name, id = f.FieldId };

@foreach(var item in  ViewBag.fields)
{
@item.name//error, cannot find the definition of name
}

And i tried also this.

@foreach(var item in  ViewBag.fields)
{
@item[0]//error, 'object' does not contain a definition for 'name'
}

However, if do this

@foreach(var item in ViewBag.fields)
{
@item 
}

it render

{name = Document, id=1}

What do i have to do?

1 Answers1

1

nemesv's link explains why this doesn't work, you basically are forced to create a named type rather than using an anonymous type. You could use Tuple, but you would have to convert the results to an IEnumerable first because Linq to Entities can't use constructor parameters.

So either create a type to transfer the data or do this:

ViewBag.fields = (from f in db.Fields
                where f.FieldId == id
                select new { name = f.Name, id = f.FieldId })
                .AsEnumerable()
                .Select(x => new Tuple<string, int>(x.name, x.id);

Then in view

@foreach(var item in ViewBag.fields)
{
    item.Item1
}
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291