Reputation: 1033
I have a model that takes smaller models as lists:
public class MostPlayedList
{
public IList<MostPlayed> mostPlayed = new List<MostPlayed>();
public IList<SongNominator> songNominator = new List<SongNominator>();
public IList<MostUpvoted> songsUpvoted = new List<MostUpvoted>();
public IList<MostUpvoting> userUpvoting = new List<MostUpvoting>();
}
The other models are hybrid viewmodels that contain information relevant for the view. Now I fill these lists up in the control using the example below:
MostPlayedList s = new MostPlayedList();
var mostPlayed = db.Songs.OrderBy(n => n.timesPlayed).ToList().Take(5);
Then for each item found, I add to the IList, in this case the MostPlayed
IList:
//most played songs
foreach (var item in mostPlayed)
{
s.mostPlayed.Add(new MostPlayed() { name = item.name, timePlayed = item.timesPlayed });
}
I do this for the other list items, then pass it into the partial view like so:
return PartialView(s);
The problem I'm having is on the view, how do I drill down and expose the relevant list items? I tried using this in the partial view:
@model IEnumerable<JayVumic.Models.MostPlayedList>
And then using for each:
@foreach (var item in Model.) {
But this doesn't seem to be working, what would be the best way to expose this model and loop through the data of a given IList?
Upvotes: 0
Views: 120
Reputation: 14316
If you want to treat each list individually you should do what Dmitry suggested in a comment. Create 4 foreach loops and display what has to be displayed for each collection.
@foreach (var item in Model.mostPlayed ) {
...
}
@foreach (var item in Model.songNominator ) {
...
}
@foreach (var item in Model.songsUpvoted ) {
...
}
@foreach (var item in Model.userUpvoting ) {
...
}
However if your smaller models share the same part, and you want to treat them alike, (it seems they don't, but think of it as an interesting fact for the future) you can extract a common interface from them. Than you can make MostPlayedList implement IEnumerable and return concated lists. Than you could use only one foreach loop on Model.
public class MostPlayedList : IEnumerable<YourCommonInteface>
{
public IList<MostPlayed> mostPlayed = new List<MostPlayed>();
public IList<SongNominator> songNominator = new List<SongNominator>();
public IList<MostUpvoted> songsUpvoted = new List<MostUpvoted>();
public IList<MostUpvoting> userUpvoting = new List<MostUpvoting>();
public IEnumerator<YourCommonInteface> GetEnumerator()
{
return mostPlayed.Concat(songNominator).Concat(songsUpvoted).Concat();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Upvotes: 1