2012-03-27 101 views
0

是否可以在一个视图中放置2个模型?我的页面是工作的罚款有一个模型,但是当我尝试添加其他模型线以下我的代码决定开始有一些错误:在1视图中有2个模型的方法,可以吗?

@model ProjectShop.Models.Delivery 

我的代码之前,我添加上面一行的作品显示如下:

@model ProjectShop.Models.Products 

@{ 
ViewBag.Title = "Products"; 
Layout = "~/Views/Shared/_ProductLayout.cshtml"; 
} 

<p>@Html.DisplayFor(model => model.productname) </p> 

在一个视图中有两个模型使我可以从两个来源调用数据的方法是什么?

编辑:

这是一类新的将作为HTML页面视图模型,但我认为它不是正确的在所有:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using ProjectShop.Models; 

namespace ProjectShop.ViewModels 
{ 
public class ProductDelivTimes 
{ 


     public Models.Products; 
     public Models.Delivery; 

} 
} 

编辑:

public class ProductDelivTimes 
{ 


    public Models.Products ProductModel; 
    public Models.Delivery DeliveryModel; 

} 

在我的HTML文件中:

@model IEnumerable<ProjectShop.ViewModels.ProductDelivTimes> 

编辑:

@model IEnumerable<ProjectShop.ViewModels.PerformanceTimes> 
@{ 

Layout = "~/Views/Shared/_Layout.cshtml"; 
var grid = new WebGrid(Model, rowsPerPage: 5, defaultSort: "Name"); 

ViewBag.Created = TempData["ProductCreated"]; 
ViewBag.Created = TempData["ProductDeleted"]; 
} 

@grid.GetHtml(
    tableStyle: "grid", 
    headerStyle: "gridhead", 
    rowStyle: "gridRow", 
    alternatingRowStyle: "gridRow", 
    mode: WebGridPagerModes.All, 
    columns: grid.Columns(

grid.Column("Image", format: @<text><img src="@item.image" alt="" width="84px" height="128px"/></text>, style: "Image"), 


grid.Column("Products", format: @<text>@Html.Raw(item.Products.name.Substring(0, item.Products.name.IndexOf(".") + 1))</text>, style: "Products") 


        )) 

回答

2

也许编写一个包含两个数据源模型,并决定哪一个在需要的时候从,获取数据的包装模式?

+0

数据将始终需要,其他所需的模型将显示页面上每个产品的交付日期。 – Blob 2012-03-27 15:25:43

+0

是的,所以只需将它们组合成一个“包装”模型,知道如何组合来自两种不同模型的数据以供显示。 – Attila 2012-03-27 15:33:54

5

如果你想有多个域的实体作为视图的一部分,考虑创建结合了两个数据源模型

喜欢的东西(只是伪代码)视图模型:

ProductDeliveryViewModel 
{ 
    // ProductModel 
    // DeliveryModel 
} 

所以你本来

@model ProjectShop.Models.ProductDeliveryViewModel 

@Html.DisplayFor (model=> model.ProductModel.Property) 
@Html.DisplayFor (model=> model.DeliveryModel.Property) 
+0

谢谢。我试图创建我的视图模型,但是当我尝试将我的模型输入到类中时出现语法错误:Models.Products;和Model.Delivery;请你能提供建议吗?谢谢 – Blob 2012-03-27 15:53:00

+0

对不起,我不明白,你可以用你的ViewModel更新你的问题 – kd7 2012-03-27 16:33:30

+0

对不起,请参阅原文中的编辑。谢谢 – Blob 2012-03-27 16:48:28

2

的球队,我已经对将使用一个ViewModel类这两个业务对象包装成可以通过视图中使用的一个对象。它可以像为每个对象拥有一个属性一样简单。

1

在过去,我通过使用第三个“容器”模型来实现这一目标。

public class MainModel 
{ 

    public ProductModel productModel {get;set;} 
    public DeliveryModel deliveryModel {get;set;} 

} 
相关问题