Im trying to pass a linq list object from my controller to my view. The linq object contains a grouping which is throwing some sort of error. I just want to display the grouped objects in a view. The linq statement works perfectly but displaying the statement doesn’t! 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 changing 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 item passed into the dictionary is of type ‘System.Collections.Generic.List1[<>f__AnonymousType72[<>f__AnonymousType63[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]]’.
Don’t try to pass anonymous types into the view as a model.
What you need is a ViewModel:
Then change your query to select into your viewmodel
And finally you can access your result in the view with the @model: