c# - 为什么将 ViewModel 传递给 View 时会出现此错误?
问题描述
将 ViewModel 传递给 View 时出现错误
传递到 ViewDataDictionary 的模型项的类型为“System.Collections.Generic.List'1[TraficAlert.Models.TaBarHeader]”,但此 ViewDataDictionary 实例需要类型为“System.Collections.Generic.IEnumerable”1[的模型项TraficAlert.Models.ViewModels.HeaderTelegramaViewModel]'。
我尝试在 中使用@model IEnumerable<TraficAlert.Models.ViewModels.HeaderTelegramaViewModel>
它Index.cshtml
并且它可以工作,但我需要从HeaderTelegramaViewModel
.
索引.cshtml:
@model IEnumerable<TraficAlert.Models.ViewModels.HeaderTelegramaViewModel>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.TaBarHeader.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.TaBarHeader.ParentId)
</th>
<th>
@Html.DisplayNameFor(model => model.TaBarHeader.TStamp)
</th>
(...)
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.TaBarHeader.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.TaBarHeader.ParentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.TaBarHeader.TStamp)
</td>
(...)
<td>
<a asp-action="Edit" asp-route-id="@item.TaBarHeader.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.TaBarHeader.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.TaBarHeader.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
标头电报控制器:
(...)
public IActionResult Index()
{
var applicationDbContext = _unitofwork.BarHeader.GetAllBarH().ToList();
return View(applicationDbContext);
}
TaBarHeaderRepository:
public IEnumerable<TaBarHeader> GetAllBarH()
{
return _db.TaBarHeaders
.Include(t => t.CategoriaFk)
.Include(t => t.CauzaFk)
.Include(t => t.ClasaFk)
.Include(t => t.LucrareFk)
.Include(t => t.RegionalaFk)
.Include(t => t.UserFk);
}
HeaderTelegramaViewModel:
public TaBarHeader TaBarHeader { get; set; }
public IEnumerable<SelectListItem> Categoria { get; set; }
public IEnumerable<ViewOtf> ViewOTFCollection { get; set; }
(...)
为什么我会收到上述错误?
谢谢你。
解决方案
我假设一个可能的错误可能来自您的表头尝试指定一个索引,考虑到您的模型是IEnumerable
.
所以改变
@Html.DisplayFor(modelItem => item.TaBarHeader.Id)
像这样
@Html.DisplayFor(modelItem => item[0].TaBarHeader.Id)
推荐阅读
- git - 临时保存当前 Git 工作树状态?
- php - 使用 PHP 使用查询更新数据库中的配置文件详细信息
- coq - i 和 tt 名字的由来是什么?
- javascript - 输入值更改导致字体导入
- docker - 链码容器应该留在哪个 docker 网络中?
- c# - 使用 c# 在 json.net 中使用 LINQ 创建树层次结构
- ios - 如何使用 OpenAL 在 IOS 上播放 Ogg/Vorbis 声音?
- sql-server - MSSQL View to MS Access 2016 Linked Table Real 不作为双精度导入
- excel - VLookup VBA 函数总是返回空字符串
- c++ - 为什么 &a 和 c++ 中的静态数组相同?