2013-07-23 84 views
2

我有一個Index View與一個表填充List屬性的數據,但是當我發佈窗體的表,該屬性爲空。MVC發送一個對象列表

這裏是型號:

public class BillViewModel 
{ 

    public List<Product> ListProducts { get; set; } 

} 

這裏是產品的看法:

public class Product 
{ 
    public int ProductId { get; set; } 
    public string ProductName { get; set; } 
    public decimal Price { get; set; } 
} 

這裏是查看:

@using (Html.BeginForm()) 
{ 

<input type="submit" value="Aceptar"/> 


<table id="tabla"> 


    @foreach (var item in Model.ListProducts) 
    { 
     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.ProductName) 
      </td> 
     </tr> 
    } 

</table> 
} 

我可以添加或刪除產品,但如何我可以在控制器中獲得產品列表嗎?:

[HttpPost] 
    public ActionResult Index(BillViewModel billViewModel) 
    { 


     return View(); 
    } 
+2

請查看這個答案:http://stackoverflow.com/questions/ 17450772/asp-net-mvc4-dynamic-form-generation/17451048#17451048這是同樣的問題,我相信它會解決你的問題。 –

+0

是的,你可以在你的控制中獲得所有細節。 Mvc流程是該控制器與模態和視圖進行通信。 –

回答

4

這是相當容易的,所有你需要做的就是發生在表單中的所有項目屬性,所以是這樣的:

<input type="submit" value="Aceptar"/> 
<table id="tabla"> 
    @for (int i = 0; i < Model.ListProducts.Count; i++) 
    { 
     <tr> 
      <td> 
       @Html.HiddenFor(x => x.ListProducts[i].ProductId) 
       @Html.HiddenFor(x => x.ListProducts[i].Price) 
       @Html.DisplayFor(x => x.ListProducts[i].ProductName) 
      </td> 
     </tr> 
    } 
</table> 
+1

是的,我使用一個for而不是一個foreach給列表的索引,每個屬性。全部使用HiddenFor。它的工作原理。 –

+0

@DiegoUnanue很高興它:)隨意標記爲答案,如果它是你在找什麼:)祝你好運。乾杯 –

+0

如果我添加一個新行,會發生什麼情況,例如我有一個可以添加新產品的文本框,此產品不在數據庫中,因此它沒有id。我可以使用什麼arquitectural aprouch來發送所有產品並將不在其中的數據插入數據庫。它具有ProductId和ProductName,我可以找到那些不在數據庫中的名稱。但是,如果我可以重複productNames? –