将模型添加到视图.net MVC 4

时间:2012-07-25 16:59:16

标签: c# asp.net-mvc-3 razor

是否可以在同一视图中使用两个模型(我的视图强烈输入到我的模型中,我需要在同一视图中修改另一个模型)。有没有办法做到这一点

2 个答案:

答案 0 :(得分: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 
}

现在进入你的Action方法

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 :(得分:1)

创建一个组合两个模型的模型。这很常见:

 public class CombinedModel
    {

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


    }