I have a view where I display a model, but at the model I want to also display a small table of data from another model that comes from the following linq in the controller
var StudentRatings = db.LearnerRatings
.Where(i => i.LessonId == id)
.GroupBy(i => i.Rating)
.Select(group => new { Rating = group.Key, TotalCount = group.Count() });
ViewBag.Ratings = StudentRatings;
I'm already returning another model from the controller, so have added this to the ViewBag. I thought I would be able to iterate through these with a foreach
foreach (var ratings in ViewBag.Ratings){
@ratings.TotalCount
}
but get an error - Additional information: 'object' does not contain a definition for 'TotalCount'
I take it this has to be cast? If so what does it get casted to?
Is this the best approach for the above?
Anonymous types should not traverse method boundaries: that is, your View doesn't know what type ratings
is.
Change your anonymous type to a named struct or class, then you can do it like so:
class Rating {
public Int32 Rating { get; set; }
public Int32 TotalCount { get; set; }
}
...
.Select(group => new Rating { Rating = group.Key, TotalCount = group.Count() });
...
foreach(Rating rating in ViewBad.Ratings) {
@rating.TotalCount
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.