当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - ViewBag Does not render its values

问题描述:

This question already has an answer here:

  • Stuffing an anonymous type in ViewBag causing model binder issues

    1 answer

网友答案:

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
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: