Reputation: 69
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__AnonymousType7
2[<>f__AnonymousType63[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.Object,FYPSchoolApp.DAL.ClassInstanceDetail]]'.
Upvotes: 3
Views: 1987
Reputation: 139758
Don't try to pass anonymous types into the view as a model.
What you need is a ViewModel:
public class AbsentCountViewModel
{
public DateTime absentDate { get; set; }
public int numAbsences { get; set; }
}
Then change your query to select into your 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);
And finally you can access your result in the view with the @model:
@model List<AbsenctCountViewModel>
Upvotes: 2