2012-07-25 53 views
0

是否有可能在同一視圖中使用兩個模型(我的視圖強類型爲我的模型,我需要在同一視圖中修改另一個模型)。有沒有辦法做到這一點將模型添加到視圖.net MVC 4

回答

2

使用ViewModel具有的屬性來代表你的其他models和傳遞的一個對象的View

public class CustomerViewModel 
{ 
    public int ID { set;get;} 
    public string Name { set;get;} 
    public Address Address {set;get;} 
    public IList<Order> Orders {set;get;} 

    public CustomerViewModel() 
    { 
    if(Address==null) 
     Address=new Address(); 

    if(Orders ==null) 
     Orders =new List<Order>(); 
    } 
} 

public class Address 
{ 
    public string AddressLine1 { set;get;} 
    //Other properties 
} 

public class Order 
{ 
    public int OrderID{ set;get;} 
    public int ItemID { set;get;} 
    //Other properties 
} 

現在您的操作方法

public ActionResult GetCustomer(int id) 
{ 
    CustomerViewModel objVM=repositary.GetCustomerFromId(id); 
    objVm.Address=repositary.GetCustomerAddress(id); 
    objVm.Orders=repositary.GetOrdersForCustomer(id); 
    return View(objVM); 
} 

你的觀點將被輸入到CustomerViewModel

@model CustomerViewModel 
@using(Html.BeginForm()) 
{ 
    <h2>@Model.Name</h2> 
    <p>@Model.Address.AddressLine1</p> 
    @foreach(var order in Model.Orders) 
    { 
    <p>@order.OrderID.ToString()</p> 
    } 

} 
1

創建一個模型,結合這兩個模型。這是很常見的:

public class CombinedModel 
    { 

     public ModelA MyFirstModel { get; set; } 
     public ModelB MyOtherModel { get; set; } 


    } 
+0

也被稱爲 「視圖模型」 – 2012-07-25 17:04:50

相關問題