简体   繁体   中英

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

This is my layout from where I calling the partial veiw.
This is the code where i got error.

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>

This is my partial view.

@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>

Change the code like this. Make sure to add the reference @using System.Collections.Generic for List.

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

Your @model is IEnumerable<T> , which is fine, but you can't create an instance of an interface. You have to pass a collection derived from IEnumerable<T> . If you want to pass an empty collection - you could use new List<T>() or Enumerable.Empty<T>() etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM