2014-01-10 26 views
1
<% using (Html.BeginForm("Action", "Controller", FormMethod.Post)) 
{%> 
<%: Html.AntiForgeryToken()%> 
<%: Html.HiddenFor(m=>m.Id) %> 
<% for (int i = 0; i < Model.CollectionOfItems.Count; i++) 
    {%> 
    <%: Html.HiddenFor(m =>Model.CollectionOfItems.ToList()[i].Id)%> 
    <%: Html.HiddenFor(m =>Model.CollectionOfItems.ToList()[i].Name)%> 
    <%: Html.EditorFor(m => Model.CollectionOfItems.ToList()[i].NumbersToState)%> 
<%} %> 
    <input type="submit" value="submit"/> 
<%} %> 

問題是當我發佈模型到控制器操作。 「CollectionOfItems」的計數爲0.模型狀態有效,沒有編譯錯誤。MVC post模型 - 收藏屬性沒有元素

編輯1:我收到屬性模型 - Id。 編輯2:控制器動作

[HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult Action(Model ReceivedModel) 
     { 
      try 
      { 
       //here i have break point to check value of ReceivedModel 
       // here i can read the value id of the received model - for ex.: 5 
      } 
      catch (Exception) 
      { 
       return "" 
      } 
     } 

編輯3: 模型是實體從ADO實體數據模型genereted

public partial class Model 
    { 
     public Model() 
     { 
      this.CollectionOfItems= new HashSet<Items>(); 
     } 
     public int Id{ get; set; } 
     public virtual ICollection<Items> CollectionOfItems{ get; set; } 
    } 

編輯4:

這是從foreach循環的結果

<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." name="[0].Id" type="hidden" value="21"> 
+1

你可以在你創建模型的地方顯示控制器方法嗎? – Andrei

+0

請發佈控制器代碼! – Fals

+0

我發佈我的編輯 – user2831001

回答

3

的.ToList()被打破了綁定到父對象。

這是ViewModel概念顯示其價值的地方之一。如果你引入一個模型對象,並且使用該模型對象來保存它(而不是僅僅將數據模型用作視圖模型),那麼你應該能夠克服這一點。

例視圖模型對於這種情況:

public class ViewModel1 // Find a better name ;) 
{ 
    public ViewModel1() 
    { 
    } 
    public int Id{ get; set; } 
    public List<Items> Items{ get; set; } 
} 
+0

這是非常好的,但我不能使用我的模型,只有從ADO.NET實體數據模型生成的實體 – user2831001

+0

我按照您的建議添加ViewModel來更改我的程序,並解決了問題。謝謝。 – user2831001

1

我有一個類似的問題。問題是每個字段的Name屬性。每個Name必須是唯一的並且與模型正確對應。以下是您需要擁有以發佈ICollection。

<% for (int i = 0; i < Model.CollectionOfItems.Count; i++) 
    {%> 
     <%: Html.Hidden("CollectionOfItems[" + i + "].Id", Model.CollectionOfItems.ElementAt(i).Id)%> 
     <%: Html.Hidden("CollectionOfItems[" + i + "].Name", Model.CollectionOfItems.ElementAt(i).Name)%> 
     <%: Html.Editor("CollectionOfItems[" + i + "].NumbersToState", Model.CollectionOfItems.ElementAt(i).NumbersToState)%> 
    <%} 
    %>