读取ViewBag匿名类

关于遍历 viewBag匿名类错误

EF tt生成的类

image

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

1 public ActionResult Index()

2 {

3 

4     MyTestEntities1 db = new MyTestEntities1();

5 

6     var source = from c in db.Student select new { c.DocId, c.StuAge, c.StuName };

7     ViewBag.source = source;

8     return View();

9 }

 

image

 

解决方法:

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

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

 

 1 public ActionResult Index()

 2 {

 3 

 4     MyTestEntities1 db = new MyTestEntities1();

 5 

 6     //var source = from c in db.Student select new { c.DocId, c.StuAge, c.StuName };

 7     //var source = from c in db.Student.ToList() select Tuple.Create(c.DocId, c.StuAge, c.StuName); //new {c.DocId,c.StuAge,c.StuName };

 8     var source = db.Student.ToList().Select(s => Tuple.Create(s.DocId, s.StuAge, s.StuName));

 9     ViewBag.source = source;

10     return View();

11 }

 

 1 <table>

 2     @foreach (var item in ViewBag.source)

 3     {

 4         <tr>

 5             <td>@item.Item1</td>

 6             <td>@item.Item2</td>

 7             <td>@item.Item3/td>

 8         </tr>

 9     }

10 </table>

11 

12  

 

 

 

 1 //

 2 // 摘要:

 3 //     创建新的 3 元组,即三元组。

 4 //

 5 // 参数:

 6 //   item1:

 7 //     此元组的第一个分量的值。

 8 //

 9 //   item2:

10 //     此元组的第二个分量的值。

11 //

12 //   item3:

13 //     此元组的第三个分量的值。

14 //

15 // 类型参数:

16 //   T1:

17 //     此元组的第一个分量的类型。

18 //

19 //   T2:

20 //     元组的第二个分量的类型。

21 //

22 //   T3:

23 //     元组的第三个分量的类型。

24 //

25 // 返回结果:

26 //     值为 (item1, item2, item3) 的 3 元组。

27 public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3); 


多谢辉同学帮助

 

你可能感兴趣的:(view)