Passing linq group object to view

I am trying to pass a linq list object from my controller to my view. The linq object contains a group that is throwing some kind of error. I just want to display grouped objects in a view. The linq statement works fine, but the display of the statement fails! any help would be greatly appreciated!

controller

        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());
    }

      

View

I tried to change my view to

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

      

but still no luck and I keep getting the following error:

The model element passed to the dictionary is of type "System.Collections.Generic.List 1[<>f__AnonymousType7

2 [<> 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.Grouping`2 [System.Object, FYPSchoolApp.DAL.ClassInstanceDetail]]."

+3


source to share


1 answer


Don't try to pass anonymous types to the view as a model.

You need a ViewModel:

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

      

Then change your query to select in your view model



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);

      

Finally, you can access your result in the view using @model:

@model List<AbsenctCountViewModel>

      

+2


source







All Articles