【发布时间】:2020-09-07 22:38:21
【问题描述】:
由于line,我收到以下错误:
@inject ClaveSol.Models.Category category
...
@foreach (var item in (IEnumerable<Category>)category)
{
<a class="dropdown-item" asp-asp-area="" asp-controller="Categories" asp-action="Index">
@Html.DisplayFor(modelItem => item.Name)
</a>
}
InvalidCastException: Unable to cast object of type 'ClaveSol.Models.Category' to type 'System.Collections.Generic.IEnumerable`1[ClaveSol.Models.Category]'.
AspNetCore.Views_Shared__Layout.<ExecuteAsync>b__38_1() in _Layout.cshtml, line 39
我试图将 Category 模型传递给我的 _Layout.cshtml 视图并迭代它的 Name 属性值。
我关注了this tuto。我在 foreach 中添加了(IEnumerable) 转换(here),因为我得到了CS1579 error。
我该如何解决?
编辑:
难道没有其他方法可以在不使用注入的情况下获取类别模型吗?还是这种局部视图的最佳方式?
【问题讨论】:
-
ClaveSol.Models.Category 类别将其更改为 IEnumerable
类别并将 (IEnumerable ) 类别中的 var 项更改为类别中的 var 项。希望它应该工作 -
@user13422309 项目在 foreach 中返回 null
标签: c# asp.net-mvc asp.net-core dependency-injection