0

我知道这很简单,但我想不通:(

我收到此错误:

传入字典的模型项的类型为“System.Collections.Generic.List 1[<>f__AnonymousType35[System.String,System.String,System.String,System.Nullable 1[System.DateTime],System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[MvcApplication3.Order]”。

这是我的控制器的代码:

    var query = from o in db.Orders
                join c in db.Customers on o.CustomerID equals c.CustomerID
                where o.CustomerID == q
                select new
                {
                    o.CustomerID,
                    o.ShipAddress,
                    o.ShipCity,
                    o.ShippedDate,
                    c.ContactName
                };

    /*
    var query = from o in db.Orders
                where o.CustomerID == q
                select o;
    */
    return View(query.ToList());

这是我的看法:

@model IEnumerable<MvcApplication3.Order>


@{
    ViewBag.Title = "Search";
}

<h2>Search</h2>
Your search results contains @Model.Count() rows

<table>
    <tr>
        <td>Customer ID</td>
        <td>Address</td>
        <td>City</td>
        <td>Shipped to Date</td>
    </tr>
@foreach (var item in Model)
{
    <tr>
        <td>@item.CustomerID</td>
        <td>@item.ShipAddress</td>
        <td>@item.ShipCity</td>
        <td>@item.ShippedDate</td>
        <td>@item.Customer.ContactName</td>

    </tr>
}
</table>

我假设它与 View 的设置方式有关。如果我删除 return View() 并仅循环来自控制器的数据,我会得到我期望的结果。任何帮助将不胜感激。

提前致谢!

4

2 回答 2

1

编辑:

试试这个:

select new Order()
                    {
                        CustomerId = o.CustomerID,
                        ShipAddress = o.ShipAddress,
                        ShipCity = o.ShipCity,
                        ShippedDate = o.ShippedDate,
                        Customer = new Customer()
                              {
                                 ContactName = c.ContactName
                              }
                    };

你没有指定型号。您创建了一个List匿名对象,并且视图需要一个IEnumerable<Order>.

于 2012-12-16T20:03:21.977 回答
0

你也可以像这样尝试。

var query = (from o in db.Orders
                join c in db.Customers on o.CustomerID equals c.CustomerID
                where o.CustomerID == q
                select c);

并鉴于您可以将其更改为

@model IEnumerable < MvcApplication3.Customers >

于 2014-11-26T09:27:38.843 回答