IEnumerable和IList的问题

时间:2013-12-19 11:30:09

标签: c# asp.net asp.net-mvc

我遇到了一些危机,我对C#,MVC 3还不熟悉,所以我很难理解这一点。基本上我的视图页面应该输出数据库中的项目列表。

我接受了这个问题 -

  

System.InvalidOperationException:传递到字典中的模型项的类型为'System.Collections.Generic.List 1[Shipments.Data.shipment_order]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [Shipments.Data.DATA]'。

来自我的控制器 -

public ActionResult Orders()
{
    IList<shipment_order> list = _shipmentSearchService.GetShipmentOrders();
    return View(list);
}

从我的观点来看,使用ASPX也不是剃须刀。

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Shipments.Data.DATA>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Orders
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Orders</h2>

<p>
    <%: Html.ActionLink("Create New", "Create") %>
</p>
<table>
    <tr>
        <th>
            DefaultContainerName
        </th>
        <th>
            CommandTimeout
        </th>
        <th></th>
    </tr>

<% foreach (var item in Model) { %>
    <tr>
        <td>
            <%: Html.DisplayFor(modelItem => item.DefaultContainerName) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.CommandTimeout) %>
        </td>
        <td>
            <%: Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %> |
            <%: Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) %> |
            <%: Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }) %>
        </td>
    </tr>
<% } %>

</table>

</asp:Content>

我尝试将<IEnumerable<Shipments.Data.DATA>>更改为<Shipments.Data.DATA>。但它只是抛出一个不同的错误,非常确定我需要使用它。任何帮助都会很棒,谢谢!

3 个答案:

答案 0 :(得分:2)

错误遵循您的声明。您的视图需要IEnumerable<Shipments.Data.DATA>

Inherits="System.Web.Mvc.ViewPage<IEnumerable<Shipments.Data.DATA>>

但你的控制器给它一个IList<shipment_order>

IList<shipment_order> list = _shipmentSearchService.GetShipmentOrders();

所以系统做了它应该做的事情 - 而不是做你对它的期望; - )......

答案 1 :(得分:2)

将视图的顶部更改为:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<Shipments.Data.DATA>>" %>

关键部分是:

Inherits="System.Web.Mvc.ViewPage<IList<Shipments.Data.DATA>>

在您的控制器中,您传递的对象list类型为IList<shipment_order>

在您的视图中,您已将ViewPage设置为IEnumerable<shipment_order>

这就是你获得该异常的原因,因为你无法隐式地从IEnumberable转换为IList,反之亦然

答案 2 :(得分:0)

尝试 List<Shipments.Data.shipment_order>