2016-11-30 112 views
2

我創建了一個稱爲CompetitionRoundModel視圖模型這部分低於生產:問題與模型綁定

public class CompetitionRoundModel 
{ 
    public IEnumerable<SelectListItem> CategoryValues 
    { 
     get 
     { 
      return Enumerable 
       .Range(0, Categories.Count()) 
       .Select(x => new SelectListItem 
       { 
        Value = Categories.ElementAt(x).Id.ToString(), 
        Text = Categories.ElementAt(x).Name 
       }); 
     } 
    } 

    [Display(Name = "Category")] 
    public int CategoryId { get; set; } 

    public IEnumerable<Category> Categories { get; set; } 

    // Other parameters 
} 

我已經結構化模型這種方式,因爲我需要根據存儲在CategoryValues值來填充下拉列表。所以對我的看法,我有:

@using (Html.BeginForm()) 
{ 
    <div class="form-group"> 
     @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownListFor(model => model.CategoryId, Model.CategoryValues, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" }) 
     </div> 
    </div> 
    // Other code goes here 
} 

我在DropDownListFor()方法選擇model.CategoryId,因爲我要選擇的值綁定到CategoryId。我真的不在乎CategoryValues,我只是需要它來填充DropDown。

我現在的問題是,當我的控制器接收爲我的行動方法模式的值,CategoryValues爲空,從而導致系統拋出所強調的是return EnumerableArgumentNullException(線路。

我甚至嘗試[Bind(Exclude="CategoryValues")],但沒有任何改變,任何幫助將不勝感激

+0

謝謝@StephenMuecke。您的解決方案奏效我只是不知道如何在這裏將你的評論標記爲「答案」,以便你信任。 –

回答

1

你不能(也不應該)創建表單控件在您的收藏IEnumerable<Category>每個Category的每個屬性,以便在您的POST方法中,Categoriesnull(它永遠不會被初始化)。只要您嘗試CategoryValues,並且您的.Range(0, Categories.Count())代碼行在getter中拋出異常。

變化查看模型,得到CategoryValues簡單geter /設定部,並刪除Categories屬性

public class CompetitionRoundModel 
{ 
    public IEnumerable<SelectListItem> CategoryValues { get; set; } 
    [Display(Name = "Category")] 
    public int CategoryId { get; set; } 
    .... // Other properties 
} 

並填充在控制器方法SelectList,例如

var categories db.Categories; // your database call 
CompetitionRoundModel model = new CompetitionRoundModel() 
{ 
    CategoryValues = categories.Select(x => new SelectListItem() 
    { 
     Value = x.Id.ToString(), 
     Text = x.Name 
    }, 
    .... 
}; 
return View(model); 

或備選地

CompetitionRoundModel model = new CompetitionRoundModel() 
{ 
    CategoryValues = new SelectList(categories, "Id", "Name"), 

否如果您返回視圖(因爲ModelState無效,您需要重新填充CategoryValues的值(請參閱The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable'瞭解更多詳情)

0

由於CategoryValues只是填充下拉,它不會回發到服務器,你需要重建從數據庫的列表之前在GET或POST操作中使用它。CategoryId屬性是值將從DropDownList發佈回服務器。