ARK
ARK
CC#
Created by ARK on 2/7/2024 in #help
Display many-to-many table data using view model in controller in ASP.NET Core MVC
I want to display many-to-many table data using a view model in controller but I get this error:
CS0029: Cannot implicitly convert type 'Website.Model.PostModel' to 'System.Collections.GenericList<Website.Model.PostModel>'
Model:
c#
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; }
}
c#
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:
c#
public class CardsViewModel
{
public List<PostModel>? PostCard { get; set; }
}
c#
public class CardsViewModel
{
public List<PostModel>? PostCard { get; set; }
}
Controller:
c#
[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);
}
c#
[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 -->
}
@using RecipeWebsite.ViewModels.CardsViewModel

@model CardsViewModel

@foreach (var item in Model.PostCard)
{
<!-- HTML -->
}
When the controller is used without view model, it works without error. Example:
c#
[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#
[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);
}
11 replies