You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 5 MVC自定义视图模型无法显示数据库表数据问题

解决ASP.NET Core 5 MVC中自定义视图模型无法展示数据库数据的问题

问题核心在于你实现的CinemasService.GetAllCinimas方法没有从数据库读取真实数据,只是创建了空对象。你需要修改这个方法,从数据库获取Cinema实体后,通过LINQ投影转换为自定义视图模型CinimaViewModels。

修正服务方法

确保CinemasService已注入数据库上下文(DbContext),然后修改GetAllCinimas方法:

public class CinemasService : ICinemasService
{
    private readonly AppDbContext _context;

    // 构造函数注入DbContext
    public CinemasService(AppDbContext context)
    {
        _context = context;
    }

    public IQueryable<CinimaViewModels> GetAllCinimas()
    {
        // 从数据库查询Cinema实体,投影到视图模型
        return _context.Cinemas.Select(cinema => new CinimaViewModels
        {
            Logo = cinema.Logo,
            Name = cinema.Name
        });
    }
}

在控制器中调用服务

在控制器中获取视图模型列表并传递给视图:

public class CinemasController : Controller
{
    private readonly ICinemasService _cinemasService;

    public CinemasController(ICinemasService cinemasService)
    {
        _cinemasService = cinemasService;
    }

    public IActionResult Index()
    {
        // 调用服务方法,转换为List传递给视图
        var cinemaViewModels = _cinemasService.GetAllCinimas().ToList();
        return View(cinemaViewModels);
    }
}

视图中展示数据

确保视图的模型类型为IEnumerable<CinimaViewModels>,然后遍历展示数据:

@model IEnumerable<CinimaViewModels>

<h1>Cinemas List</h1>
<table class="table table-striped">
    <thead>
        <tr>
            <th>Logo</th>
            <th>Cinema Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var vm in Model)
        {
            <tr>
                <td><img src="@vm.Logo" alt="@vm.Name" style="width: 80px;" /></td>
                <td>@vm.Name</td>
            </tr>
        }
    </tbody>
</table>

额外注意事项

  1. 实体与表映射:如果数据库表名为cinimas,需在Cinema实体上添加[Table("cinimas")]特性,确保EF Core能正确映射到该表。
  2. 属性名匹配:确认CinimaViewModels的Logo、Name属性名和Cinema实体的对应属性名完全一致,避免投影时出现赋值错误。
  3. IQueryable的优势:保持返回IQueryable<CinimaViewModels>可让你在控制器层添加分页、过滤等逻辑,避免提前加载所有数据,提升性能。

内容的提问来源于stack exchange,提问作者ahmed barbary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:15:32