2011-09-06 115 views
0

你能帮我理解泛型集合有什么问题吗?提前致谢!ASP.Net MVC模型问题

错误:传递到字典中的模型项类型为'System.Collections.Generic.List 1[DomainModel.Product]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [DomainModel.Entities.Product]'。

MODEL:

namespace DomainModel.Concrete 
{ 
    public class SqlProductsRepository : IProductsRepository 
    { 
     private Table<Product> productsTable; 

     public SqlProductsRepository(string connString) 
     { 
      productsTable = (new ProaductDataContext(connString)).GetTable<Product>(); 
     } 

     public IQueryable<Product> Products 
     { 
      get { return productsTable; } 
     } 
    } 
} 

接口

namespace DomainModel.Abstract 
{ 
    public interface IProductsRepository 
    { 
     IQueryable<Product> Products { get; } 
    } 
} 

VIEW

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ViewMaster.Master" 
     Inherits="System.Web.Mvc.ViewPage<IEnumerable<DomainModel.Entities.Product>>" %> 
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
Products 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

    <% foreach (var product in Model) 
     { %> 
     <div class = "item"> 
     <h3> <%=product.Name%></h3> 
     <%= product.Description%> 
     <h4><%= product.Price.ToString("c")%></h4> 
     </div> 
     <%} %> 
</asp:Content> 

回答

5

急诊室ror消息告诉你所有你需要知道的信息;

The model item passed into the dictionary is of type 
'System.Collections.Generic.List1[DomainModel.Product]', 
but this dictionary requires a model item of type 
'System.Collections.Generic.IEnumerable1[DomainModel.Entities.Product]'. 

如果你看一下你的观点,你可以看到

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ViewMaster.Master" 
     Inherits="System.Web.Mvc.ViewPage<IEnumerable<DomainModel.Entities.Product>>" %> 

Inherits="System.Web.Mvc.ViewPage<IEnumerable<DomainModel.Entities.Product>>"是什么绊倒你。你正在传递一个IEnumerable的DomainModel.Product,但你期待别的东西。有一点很奇怪,你有两个在同一个命名空间内命名相同的类,但是不用担心,你需要确保你在控制器和视图的同一个命名空间中使用同一个类。

所以我想尝试改变你的看法,成为

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ViewMaster.Master" 
     Inherits="System.Web.Mvc.ViewPage<IEnumerable<DomainModel.Product>>" %> 

然后试图弄清楚为什么你有两个产品类别:)

+0

你是我的英雄!谢谢,我一整个早上都在忙着这个。我正在通过一本教科书中的教程,看起来这本书是一个错误。 – Susan