![](/img/trans.png)
[英]Adding a drop down view of items from another model in the user registration view (ASP.NET MVC5)
[英]adding a model to a view .net MVC 4
是否可以在同一视图中使用两个模型(我的视图是我的模型的强类型,我需要在同一视图中修改另一个模型)。 有没有办法做到这一点
使用具有属性的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>
}
}
创建一个将两个模型结合在一起的模型。 这很常见:
public class CombinedModel
{
public ModelA MyFirstModel { get; set; }
public ModelB MyOtherModel { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.