模型绑定问题

时间:2016-11-30 23:04:20

标签: asp.net-mvc model-binding

我创建了一个名为#pragma的视图模型,该模型在下面部分生成:

@numba.jit

我以这种方式构建了模型,因为我需要根据存储在CategoryValues中的值填充下拉列表。所以我认为:

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 } 方法中选择了@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 } ,因为我想将所选值绑定到model.CategoryId。我真的不在乎DropDownListFor(),我只需要它来填充DropDown。

我现在的问题是,当我的Controller在action方法中收到我的Model的值时,CategoryId为null,导致系统抛出CategoryValues(突出显示的行是{ {1}}行。

我甚至尝试过CategoryValues但完全没有变化。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您不是(也不应该)为Category集合中的每个IEnumerable<Category>的每个属性创建表单控件,因此在您的POST方法中,Categories的值为{{1 (它永远不会被初始化)。只要您尝试null,您的CategoryValues代码行就会在getter中引发异常。

更改您的视图模型,为.Range(0, Categories.Count())提供一个简单的geter / setter,并删除CategoryValues属性

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的值(有关详细信息,请参阅The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable'

答案 1 :(得分:0)

由于CategoryValues只填充下拉列表,因此它永远不会回发到服务器,并且您需要在GET或POST操作中使用它之前从数据库重建列表。 CategoryId属性是将从DropDownList发回服务器的值。