如何在视图中使用GroupBy数据 - ASP.NET MVC 4

时间:2012-08-31 14:40:15

标签: c# entity-framework group-by asp.net-mvc-4

我有以下LINQ代码。

public List<IGrouping<Guid, ProfileImage>> GetAllUser()
{
    return _profileImageRepository.QueryProfileImage()
        .GroupBy(g => g.UserId)
        .ToList();
}

这个想法是它将检索所有用户的个人资料图片,但如果用户有多个图片,则只返回最后一个图片。

我不确定这是对的,但这不是我最大的问题。

在我的控制器中,我有以下代码。

_homeViewModel.ProfileImages = _profileImageService.GetAllUser();

视图模型:

public List<IGrouping<Guid, ProfileImage>> ProfileImages { get; set; }

我的一个大问题是,如何在我的视图中使用它,以便我可以打印正确的信息。

当我查看即时Windows中的数据时,它看起来像这样:

Model.ProfileImages
Count = 2
    [0]: {System.Data.Objects.ELinq.InitializerMetadata.Grouping<System.Guid,Zipr.Models.ProfileImage>}
    [1]: {System.Data.Objects.ELinq.InitializerMetadata.Grouping<System.Guid,Zipr.Models.ProfileImage>}

我试过这样做:

<ul>
    @foreach (var image in Model.ProfileImages)
    {
        <li>
            <img src="@Url.Content(String.Format("~/Content/uploads/thumbs/{0}", image.ThumbPath))" alt="" />
        </li>
    }
</ul>

任何人都有解决方法如何访问我的属性ThumbPath等等?

1 个答案:

答案 0 :(得分:0)

似乎你对ID不感兴趣;所以更改此项以返回ProfileImage

列表
public List<ProfileImage> GetAllUser()
{
    return _profileImageRepository.QueryProfileImage()
        .GroupBy(g => g.UserId)
        .Select(u => u.First() } 
        .ToList();
}

现在,当您的视图遍历图像时,它实际上将获得ProfileImage对象,而不是IGrouping的实例