2014-06-16 67 views
-1

出於某種原因,我試圖手動綁定複雜模型的數組,但我在控制器中得到空引用異常,活頁夾不檢索參數。我發現this question這是非常相似的(唯一的區別實際上是模型的類型),但我不明白爲什麼它不起作用在我的情況。手動綁定複雜模型陣列到控制器動作

這是我的。

在我的控制器

public ActionResult MyAction(ComplexType[] models) 
{ 
    foreach(ComplexType c in models) // Exception at this point, the parameter is null 
    { 
     //Do stuff 
    } 
} 

在我看來:

@using(Html.BeginForm("MyAction","Controller")) 
    { 
     @Html.AntiForgeryToken() 
<table> 
     @for (int i = 0; i < Model._MyProperty.Count; i++) 
     { 
      var d = Model._MyProperty[i]; 
      @:<tr> 
       @:<td> @Html.CheckBox("models.Property1["+i+"]", d.Property1) 
        @Html.Hidden("models.ID["+i+"]",d.ID) 
        @Html.Hidden("models.Property2["+i+"]") 
        @Html.Hidden("models.Property3["+i+"]") 
        @Html.Hidden("models.Property4["+i+"]") 
       @: </td> 
      @:</tr> 
     } 

//Submit Button 
</table> 

} 

這裏是我的課:

class ComplexType 
{ 
    int ID {get;set;} 
    int Property1{get;set;} 
    int Property2{get;set;} 
    int Property3{get;set;} 
    int Property4{get;set;} 
} 

我試圖在改變的ComplexType []到ICollection的控制器,但它沒有工作。此外,只是爲了獲取信息,我的ViewModel不是我要綁定的模型。我需要在這個單一視圖中有多種形式處理不同的數據類型。

回答

2

你命名你的元素在循環如下

<input type="hidden" name="models.Property2[0]" value 
<input type="hidden" name="models.Property2[1]" value 

當它應該是

<input type="hidden" name="models[0].Property2" value 
<input type="hidden" name="models[1].Property2" value