3

我试图将 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__AnonymousType72[<>f__AnonymousType6 3[System.Int32,System.Int32,System.Int32],System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[System.Linq.IGrouping`2[System.Object,FYPSchoolApp.DAL.ClassInstanceDetail]]”。

4

1 回答 1

2

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

你需要的是一个 ViewModel:

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

然后更改您的查询以选择到您的视图模型中

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>
于 2013-02-19T21:02:57.777 回答