![](/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.