在 Razor 视图中访问 IEnumerable 中多个表中的元素

Access elements from several tables in IEnumerable in Razor view

我想问一下我如何访问包含来自剃刀视图中多个表的不同元素的列表:

public IEnumerable Blogs { get; set; }

public async Task OnGetAsync()
{
    Blogs = await _context.Blog
            .Select(b => new
            {
                b.Id,
                b.Name,                           
                b.Owner.UserName,
            })
            .ToListAsync();

}

如何在 Razor 视图中访问它?

当我使用以下内容时:

@foreach (var b in Model.Blogs)
{
    <div> @b </div>
}

我把所有的对象都作为字符串得到了! 但是我不能使用 @b.Id 例如,我只是得到 Methods (ToString, Equal ...)

如何访问对象属性?例如:@b.Id、@b.Name ...

谢谢

更新: 假设我想使用这个:

public async Task OnGetAsync()
{
    var Blogs = await _context.Blog
            .Select(b => new
            {
                b.Id,
                b.Name,                           
                b.Owner.UserName,
            })
            .ToListAsync();

}

如何按索引访问 var 博客?

您应该创建一个 BlogViewModel class,而不是使用匿名对象,它具有您想要的三个属性:

public class BlogViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string OwnerName { get; set; }
}

那么您的查询和列表构建逻辑将是:

public List<BlogViewModel> Blogs { get; set; }

public async Task OnGetAsync()
{
     Blogs = await _context.Blog
            .Select(b => new BlogViewModel()
            {
                Id = b.Id,
                Name = b.Name,                           
                OwnerName = b.Owner.UserName,
            })
            .ToListAsync();
}

然后您可以轻松地访问剃须刀循环中的属性