将分组的linq对象传递给视图

时间:2013-02-19 20:53:48

标签: asp.net-mvc linq razor

我试图将控制器中的linq列表对象传递给我的视图。 linq对象包含一个抛出某种错误的分组。我只想在视图中显示分组对象。 linq语句完美无缺,但显示语句却没有!任何帮助将不胜感激!

控制器

        public ViewResult StudentAttendanceForYear(int id)
    {

        DateTime finDate = System.DateTime.Today;
        DateTime strtDate = DateTime.Today.AddMonths(-6);


        var chosenStudent = (from t in db.ClassInstanceDetails.Include("Student")
                                 where (t.Attendance == false) && (t.StudentID == id)
                                 && (t.ClassInstance.Date > strtDate) && (t.ClassInstance.Date < finDate)
                                 group t by new { t.ClassInstance.Date.Year, t.ClassInstance.Date.Month, t.ClassInstance.Date.Day } into grp
                                 select new
                                 {

                                     absentDate = grp.Key,
                                     numAbsences = grp.Count(t => t.Attendance == false)

                                 }).ToList();



        return View(chosenStudent.ToList());
    }

视图

我尝试将视图更改为

@model IEnumerable<System.Linq.IGrouping<object, FYPSchoolApp.DAL.ClassInstanceDetail>>

但仍然没有运气,我不断收到以下错误:

传递到字典中的模型项的类型为'System.Collections.Generic.List 1[<>f__AnonymousType7 2 [&lt;&gt; f__AnonymousType6 3[System.Int32,System.Int32,System.Int32],System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [System.Linq.IGrouping`2 [System。对象,FYPSchoolApp.DAL.ClassInstanceDetail]]”。

1 个答案:

答案 0 :(得分:2)

不要尝试将匿名类型作为模型传递到视图中。

您需要的是ViewModel:

public class AbsentCountViewModel
{
   public DateTime absentDate { get; set; }
   public int numAbsences { get; set; }
}

然后更改您的查询以选择进入您的viewmodel

var chosenStudent = 
   (from t in ...
   group t by new 
   { 
           t.ClassInstance.Date.Year, 
           t.ClassInstance.Date.Month, 
           t.ClassInstance.Date.Day 
   } into grp
   select new
   {
       absentDate = grp.Key,
       numAbsences = grp.Count(t => t.Attendance == false)
   }).ToList()
   // you need to do the select in two steps 
   // because EF cannot translate the new DateTime
   .Select(item => new AbsenctCountViewModel
   {
       absentDate = new DateTime(item.absentDate.Year, 
                                 item.absentDate.Month, 
                                 item.absentDate.Day)
       numAbsences = item.numAbsences
   }).ToList();

return View(chosenStudent);

最后,您可以使用@model:

在视图中访问您的结果
@model List<AbsenctCountViewModel>