我創建了一個稱爲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 Enumerable
線ArgumentNullException
(線路。
我甚至嘗試[Bind(Exclude="CategoryValues")]
,但沒有任何改變,任何幫助將不勝感激
謝謝@StephenMuecke。您的解決方案奏效我只是不知道如何在這裏將你的評論標記爲「答案」,以便你信任。 –