我通过遵循本教程,试图在MVC4项目的一个视图中返回两个模型。我有一个名为Product的模型,看起来像这样:
public class Product : IEnumerable<ShoppingCartViewModel>,
IList<ShoppingCartViewModel>
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
(...)
}
还有一个ViewModel,其中包含ShoppingCarts(列表)列表,如下所示:
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>
,意味着迭代Product
将给出ShoppingCartViewModel
元素。
<% foreach (Product p in ViewData.Model.product) { %>
应该 :
<% foreach (ShoppingCartViewModel p in ViewData.Model.product) { %>
但是您的设计很奇怪,也许您做得过头了?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句