关于遍历 viewBag匿名类错误

EF tt生成的类

读取ViewBag匿名类-LMLPHP

明明有值眼睁睁看着 却不认识

 public ActionResult Index()
{ MyTestEntities1 db = new MyTestEntities1(); var source = from c in db.Student select new { c.DocId, c.StuAge, c.StuName };
ViewBag.source = source;
return View();
}

读取ViewBag匿名类-LMLPHP

解决方法:

1:建立匿名类的实体类进行转换,

2:使用Tuple 按照数组方式进行读取

 public ActionResult Index()
{ MyTestEntities1 db = new MyTestEntities1(); //var source = from c in db.Student select new { c.DocId, c.StuAge, c.StuName };
//var source = from c in db.Student.ToList() select Tuple.Create(c.DocId, c.StuAge, c.StuName); //new {c.DocId,c.StuAge,c.StuName };
var source = db.Student.ToList().Select(s => Tuple.Create(s.DocId, s.StuAge, s.StuName));
ViewBag.source = source;
return View();
}
 <table>
@foreach (var item in ViewBag.source)
{
<tr>
<td>@item.Item1</td>
<td>@item.Item2</td>
<td>@item.Item3/td>
</tr>
}
</table>
 //
// 摘要:
// 创建新的 3 元组,即三元组。
//
// 参数:
// item1:
// 此元组的第一个分量的值。
//
// item2:
// 此元组的第二个分量的值。
//
// item3:
// 此元组的第三个分量的值。
//
// 类型参数:
// T1:
// 此元组的第一个分量的类型。
//
// T2:
// 元组的第二个分量的类型。
//
// T3:
// 元组的第三个分量的类型。
//
// 返回结果:
// 值为 (item1, item2, item3) 的 3 元组。
public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3); 多谢辉同学帮助
05-11 20:15