如何使用ViewModel在MVC4应用程序中实现IEnumerator

本文关键字:实现 IEnumerator 应用程序 MVC4 何使用 ViewModel | 更新日期: 2023-09-27 18:37:26

我正在尝试按照本教程在我的 MVC4 项目中的一个视图中返回两个模型。我有一个名为"产品"的模型,如下所示:

public class Product : IEnumerable<ShoppingCartViewModel>, 
                           IList<ShoppingCartViewModel>
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        (...)
    }

还有一个带有购物车列表(列表)的视图模型,如下所示:

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

但这无济于事。

如果

有人能解释如何正确实现接口成员并获得构建解决方案(如果可能),我将不胜感激。

如何使用ViewModel在MVC4应用程序中实现IEnumerator

Product继承自IEnumerable<ShoppingCartViewModel>时,这意味着迭代Product将给出ShoppingCartViewModel元素。

<% foreach (Product p in ViewData.Model.product) { %>

应该是 :

<% foreach (ShoppingCartViewModel p in ViewData.Model.product) { %>

但是你在这里的设计很奇怪,也许你做得过头了?