在 ASP.NET Core MVC 中使用控制器中的视图模型显示多对多表数据

问题描述 投票:0回答:1

我想在控制器中使用视图模型显示多对多表数据,但出现此错误:

CS0029:无法将类型“Website.Model.PostModel”隐式转换为“System.Collections.GenericList

Model

public class PostModel
{
    [Key]
    public int Id { get; set; }

    public List<TagsModel> Tags { get; set; } = new List<TagsModel>();
    public virtual List<PostTagModel> PostTags { get; set; } = new List<PostTagModel>();
}

public class TagsModel
{        
    [Key]
    public int Id { get; set; }

    public List<PostModel> Posts { get; set; }
    public virtual List<PostTagModel> PostTags { get; set; }
}

public class PostTagModel
{
    public int PostId { get; set; }
    public int TagId { get; set; }

    public virtual PostModel Post { get; set; }
    public virtual TagsModel Tag { get; set; }
}

ViewModel

public class CardsViewModel
{
    public List<PostModel>? PostCard { get; set; }
}

Controller

[HttpGet]
public async Task<IActionResult> Detail(int id)
{
    var TaggedPostVM = new CardsViewModel
    {
        PostCard = await _context.Posts.Include(t => t.PostTags) 
                                    .ThenInclude(p => p.Post)
                                    .SingleAsync(t => t.Id == id);
    };

    return View(TaggedPostVM);
}

View

@using RecipeWebsite.ViewModels.CardsViewModel

@model CardsViewModel

@foreach (var item in Model.PostCard)
{
   <!-- HTML -->
}

当控制器在没有视图模型的情况下使用时,它可以正常工作。

Example

[HttpGet]
public async Task<IActionResult> Detail(int id)
{
    var Tag = await _context.Posts
                            .Include(t => t.PostTags) 
                            .ThenInclude(p => p.Post)
                            .SingleAsync(t => t.Id == id);

    return View(Tag);
}
c# asp.net-core-mvc many-to-many asp.net-core-identity
1个回答
0
投票

在您的代码中,您将

CardsViewModel
中的 PostCard 属性定义为
List<PostModel>
,但在控制器中您尝试将 PostModel 对象传递给它,这导致了错误。

如果你想传递PostModel对象的列表,你可以修改控制器以返回一个列表,这里有一个例子你可以作为参考:

我的控制器:

[HttpGet]
public async Task<IActionResult> Detail(int id)
{
    var taggedPosts = await _context.Posts
                   .Include(t => t.PostTags)
                   .Where(t => t.Id == id)
                   .ToListAsync();

    var TaggedPostVM = new CardsViewModel
    {
        PostCard = taggedPosts
    };

    return View(TaggedPostVM);
}

查看:

@model CardsViewModel

@foreach (var post in Model.PostCard)
{
    <div>
        <p>ID: @post.Id</p>
        
    </div>
}

我的初始种子数据:

当我传入 id 值为 1 时:

我可以在页面中获取数据:

© www.soinside.com 2019 - 2024. All rights reserved.