【发布时间】:2013-10-30 16:25:59
【问题描述】:
我试图通过关注this tutorial 在我的 MVC4 项目的一个视图中返回两个模型。我有一个名为 Product 的模型,如下所示:
public class Product : IEnumerable<ShoppingCartViewModel>,
IList<ShoppingCartViewModel>
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
(...)
}
还有一个带有 ShoppingCarts (List) 列表的 ViewModel,如下所示:
public class ShoppingCartViewModel : IEnumerable<Product>, IList<Product>
{
public List<Cart> CartItems { get; set; }
public decimal CartTotal { get; set; }
}
我有一个“包装模型”,它执行以下操作:
public class ProductAndCartWrapperModel
{
public Product product;
public ShoppingCartViewModel shoppingCart;
public ProductAndCartWrapperModel()
{
product = new Product();
shoppingCart = new ShoppingCartViewModel();
}
}
然后我尝试以这种方式简单地显示具有两种不同模型的视图
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<projectname.ProductAndCartWrapperModel>" %>
(...)
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div>
<% foreach (projectname.Models.Product p in
ViewData.Model.product) { %>
<div>
<div id="ProductName"><%: p.Name %></div>
<div id="ProductPrice"><%: p.Price %></div>
</div>
<% } %>
</div>
<div>
<% foreach (projectname.ViewModels.ShoppingCartViewModel sc in
ViewData.Model.shoppingCart) { %>
<div>
<div id="Div1"><%: sc.CartItems %></div>
<div id="Div2"><%: sc.CartTotal %></div>
</div>
<% } %>
</div>
</asp:Content>
不幸的是,在尝试构建时出现一个错误
Cannot convert type 'projectname.Models.Product' to
'projectname.ViewModels.ShoppingCartViewModel'
后面是两个模型的错误列表:
does not implement interface member
'System.Collections.Generic.IEnumerable<projectname.ViewModels.ShoppingCartViewModel>.
GetEn umerator()'. 'projectname.Models.Product.GetEnumerator()' cannot implement
'System.Collections.Generic.IEnumerable<projectname.ViewModels.ShoppingCartViewModel>.
GetEnumerator()' because it does not have the matching return type of
'System.Collections.Generic.IEnumerator<projectname.ViewModels.ShoppingCartViewModel>'.
我感觉我非常接近在一个页面上显示这两个模型,但我不知道如何实现 IEnumerator 并获得匹配的类型。我尝试添加一个这样的:
public IEnumerator<Object> GetEnumerator()
{
return this.GetEnumerator();
}
但这无济于事。
如果有人能解释如何正确实现接口成员并获得构建解决方案(如果可能),我将不胜感激。
【问题讨论】:
-
为什么
Product实现IEnumerable<ShoppingCartViewModel>?如果您需要在视图中枚举 over 某些内容,只需将视图模型设置为具有IEnumerable<T>(您要枚举的对象)。您的视图模型看起来过于复杂。 -
我这样做是因为教程也是这样做的。但是好吧,我只能列举产品?以及如何在我的视图模型中制作这个 IEnumerable
?
标签: c# asp.net-mvc-4 mvvm ienumerator