ASP.Net MVC模型问题

时间:2011-09-06 17:36:17

标签: asp.net-mvc anonymous-types

你能帮我理解一下通用收藏的问题吗?提前谢谢!

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

模特:

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; }
    }
}

查看

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

1 个答案:

答案 0 :(得分:5)

错误消息告诉您需要知道的所有内容;

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>>" %>

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