I have the following LINQ statement:
var genre = model.ModelGenres.Where(q => q.Active);
var genreWithFeedbackAverage = genre
.Select(q => new { Genre = q, Average = (q.ModelRate.Interaction + q.ModelRate.Attitude + q.ModelRate.Posing) / 3 })
.GroupBy(q => q.Genre)
.Select(q => new { Genre = q.Key, Average = (int)Math.Round(q.Average(p => p.Average)) });
var debugList = genreWithFeedbackAverage.ToList();
this.ViewBag.GenreAverage = genreWithFeedbackAverage.ToList();
In the Razor View, I access the GenreAverage
:
var genres = this.ViewBag.GenreAverage;
@foreach (var genre in genres)
{
<tr>
<td>
@genre.Genre.Tag.Name
</td>
<td>
@genre.Average
</td>
</tr>
}
However, at line 4, genre.Genre
throws the following exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Genre'
I tried to debug but cannot find the reason for this exception, because the object clearly has it:
How can I fix this problem? Do I have to create a concrete class, and stop using anonnymous class?
P.s: I tried to comment out that line, and as expected, Average
is not a valid definition too.
ANSWER: The problem is similar to this topic (you cannot pass an anonnymous type in ViewBag): Stuffing an anonymous type in ViewBag causing model binder issues
I have to create a concrete class:
public class GenreWithAverageViewModel
{
public ModelGenre Genre { get; set; }
public int Average { get; set; }
}
and change the LINQ statement:
var genreWithFeedbackAverage = genre
.Select(q => new { Genre = q, Average = (q.ModelRate.Interaction + q.ModelRate.Attitude + q.ModelRate.Posing) / 3 })
.GroupBy(q => q.Genre)
.Select(q => new GenreWithAverageViewModel { Genre = q.Key, Average = (int)Math.Round(q.Average(p => p.Average)) });