首页 > 解决方案 > 为什么将 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; }
(...)

为什么我会收到上述错误?

谢谢你。

标签: c#asp.net-mvcasp.net-coreviewviewmodel

解决方案


我假设一个可能的错误可能来自您的表头尝试指定一个索引,考虑到您的模型是IEnumerable.

所以改变

@Html.DisplayFor(modelItem => item.TaBarHeader.Id)

像这样

@Html.DisplayFor(modelItem => item[0].TaBarHeader.Id)

推荐阅读