如何将 IEnumerable 模型传递给 MVC 中的局部视图

How to pass an IEnumerable model to a partial view in MVC

这是我调用部分视图的布局。
这是我出错的代码。

CS0144 Cannot create an instance of the abstract class or interface 'IEnumerable'

<div class="fa fa-group">
  @Html.Partial("_Comment", new IEnumerable<OnlineTaxiReservationSystem.Models.Comment>)
</div>

这是我的部分看法。

@model IEnumerable<OnlineTaxiReservationSystem.Models.Comment>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.UserComments)
    </th>
    @*<th>
        @Html.DisplayNameFor(model => model.UserId)
    </th>*@
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.UserComments)
    </td>
    @*<td>
        @Html.DisplayFor(modelItem => item.UserId)
    </td>*@
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.CommentId }) |
        @Html.ActionLink("Details", "Details", new { id=item.CommentId }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.CommentId })
    </td>
</tr>
}
</table>

像这样更改代码。确保为列表添加引用 @using System.Collections.Generic

<div class="fa fa-group">
    @Html.Partial("_Comment", new List<OnlineTaxiReservationSystem.Models.Comment>())
</div>

你的@modelIEnumerable<T>,没问题,但是你不能创建一个接口的实例。您必须传递从 IEnumerable<T> 派生的集合。如果你想传递一个空集合——你可以使用 new List<T>()Enumerable.Empty<T>()