在MVC中加入两个模型呈现在视图中

时间:2013-08-01 05:11:27

标签: asp.net-mvc entity-framework

我想在视图中将会计系统中的当前因素与控制器中的实体框架一起加入两个以下模型类

<pre>
namespace AccountingSystem.Models
{
    public class BuyFactor
    {
        public int BuyFactorId { get; set; }        
        public DateTime CreateDate { get; set; }        
        public string Seller { get; set; }
        public string Creator { get; set; }
        public decimal SumAllPrice { get; set; }
        public ICollection<BuyFactorDetail> BuyFactorDetails { get; set; }
    }
}

namespace AccountingSystem.Models
{
    public class BuyFactorDetail
    {
        public int BuyFactorDetailId { get; set; }         
        public int Number { get; set; }
        public string Description { get; set; }
        public decimal SumPrice { get; set; }
        public int BuyFactorId { get; set; }
        public virtual BuyFactor BuyFactor { get; set; }        
        public virtual Commodity Commodity { get; set; }        
    }
}
</pre>

6 个答案:

答案 0 :(得分:1)

创建新模型

public class JointModel
{
   public BuyFactor BuyFactor {get; set;}
   public BuyFactorDetail BuyFactorDetail {get; set;}
}

答案 1 :(得分:1)

只需创建另一个模型,然后调用其他模型

 public class ParentModel
 {
 public BuyFactor BuyFactor {get; set;}
 public BuyFactorDetail BuyFactorDetail {get; set;}
 }

所以当你在视野中调用它时

 @model IEnumerable<AccountingSystem.Models.ParentModel>

   @Html.DisplayNameFor(model => model.BuyFactor.Creator)

答案 2 :(得分:0)

最佳方式是将Model定义为主模型中的Property

例如

 public class BuyFactor
{
    public int BuyFactorId { get; set; }        
    public DateTime CreateDate { get; set; }        
    public string Seller { get; set; }
    public string Creator { get; set; }
    public decimal SumAllPrice { get; set; }
    public ICollection<BuyFactorDetail> BuyFactorDetails { get; set; }
    public BuyFactorDetail BuyFactorEntity {get;set;}
}

BuyFactorEntity中分配值并用作Model.BuyFactorEntity.BuyFactorDetailId

答案 3 :(得分:0)

使用Linq联接查询,例如

    var query = (from b in context.BuyFactors
                     join d in context.BuyFactorDetail
                     on
..
                     select new
                     {
                        BuyFactorId = b.BuyFactorId,
                        ....
                        BuyFactorDetailId = d.BuyFactorDetailId,
                        ...

    ..
                 }));

答案 4 :(得分:0)

您的BuyFactor已包含BuyFactorDetail集合。你确定实体之间的关系是1:N吗? 您可以将BuyFactor用作模型,并可以使用BuyFactor实体的BuyFactorDetails属性。

答案 5 :(得分:0)

在控制器中使用ViewBag为两者分配相应的对象。

ViewBag.BuyFactor= BuyFactor;
ViewBab.BuyFactorDetail = BuyFactorDetail;

要在视图中使用它,您必须对它们进行类型转换。