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

ASP.NET Core MVC视图中同时使用两个模型报错该如何解决?

问题原因

控制器返回给视图的是List<Musico>类型数据集,但视图绑定的是ComunaViewModel类型模型,二者类型不匹配导致报错。

修复步骤

  • 第一步:修改控制器Index方法,关联查询Musico和对应Comuna数据,组装为ComunaViewModel列表返回
public async Task<IActionResult> Index()
{
    var viewModelList = await _context.Musico
        .Join(_context.Comuna,
            musico => musico.IdComuna,
            comuna => comuna.Id,
            (musico, comuna) => new ComunaViewModel
            {
                MusicoDTO = musico,
                ComunaDTO = comuna
            })
        .ToListAsync();
    return View(viewModelList);
}
  • 第二步:在视图代码第一行添加模型绑定声明,替换为你项目中ComunaViewModel对应的实际命名空间
@model IEnumerable<你的项目命名空间.ComunaViewModel>
  • 第三步:补全视图代码,集合类型的模型调用DisplayNameFor时需要先取集合首个元素获取属性元数据
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().MusicoDTO.Nombre)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.First().MusicoDTO.Estilos)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.First().ComunaDTO.Nombre)
            </th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.MusicoDTO.Nombre)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MusicoDTO.Estilos)
             </td>
            <td>
                @Html.DisplayFor(modelItem => item.ComunaDTO.Nombre)
            </td>
        </tr>
}
    </tbody>
</table>

内容的提问来源于stack exchange,提问作者fatED.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:48:01