将列表传递给asp mvc中的aview:List vs IEnumerable

时间:2015-08-25 05:01:35

标签: c# asp.net

只是一个简单的问题。

@using MvcApplication6.Models;
@model IEnumerable<Employee>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New record", "Create")
</p>

<p>@Html.ActionLink("Check departments", "Index", "Department")</p>

<table border="1">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.firstname)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.lastname)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.department)
        </th>
        <th>Action</th>
    </tr>

@foreach (Employee item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.id)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.firstname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.lastname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.department)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id }) |
            @Html.ActionLink("Details", "Details", new { id=item.id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.id }) |
            @Html.DisplayFor(modelItem => item.Players[0])
        </td>

    </tr>


}

</table>

这就是我通过我的名单的方式:

  public ActionResult Index()
    {

        EmployeeContext emp = new EmployeeContext();
        List<Employee> adep = emp.Employees.ToList();

        return View(adep);
    }

为什么我必须在我的视图中将其声明为IEnumerable,即使我传递的只是List?就像我将IEnumerable更改为List一样,我会在这行代码中专门出错:

@Html.DisplayNameFor(model => model.id)

我在其他观点上测试它并将其声明为列表:

@model List<MvcApplication6.Models.Employee>

虽然不涉及DisplayNameForDisplayFor,但它按预期工作。

0 个答案:

没有答案